Finding the Smallest Difference

Today let’s go over finding the smallest difference between two numbers in two seperate arrays. In order to solve this problem we must find a pair of numbers whose absolute difference is closest to zero. This function should return an array containing these two numbers. It is assumed that there will only be one pair of numbers with the smallest difference. Let’s get to solving…

We begin by sorting both of the input arrays in place and then we need to create some variables to store and update information as we go along. We create index variables for both arrays, the smallest difference, the current smallest difference and a result array for the smallest pair. Then we build a loop that runs while the index variables are both less than the length of the input arrays we are looping over. Here is what that beginning of our function looks like in code.

This gets us pretty close to a solution actually, we just now need to check some conditions and if those conditions are met, we manipulate some of the variables. We check 3 conditions firstly, we see if the firstNum or the secondNum is larger and depending on which one is, we change our current variable and then increment the index variable of either the first index or the second depending on which arrays number is larger. If they’re the same number, we return the pair. In a separate conditional, we check and see if current is smaller than our smallest variable. Smallest becomes our current and we add the number from the first array and the number from the second to our smallestPair array. Finally, we return the smallestPair array.

And there is our solution to our smallest difference function! Just a fair amount of keeping track of information about the numbers in the input arrays and updating depending on conditionals. New problem next week!

Software Engineering Student at Flatiron School