Smallest Difference
16.6 Smallest Difference: Given two arrays of integers, compute the pair of values (one value in each array) with the smallest (non-negative) difference. Return the difference.
Brute force: Find min of all differences between pairs. O(N^2 + N*M), with O(N*M) extra space
The pair itself can be found by knowing the index of the location within the array. Suppose array size 1 = 3, array size 2 = 7. Then if in the min array = index location 13 would be @ row 13 % 3 = 1 in array 1, and @ row 13 % 7 = 6. (This is basically how the index of two dimensional arrays get accessed.)
Just realized we don't have to return the pair.
The other approach would be to first sort both arrays, and then use two different pointers between both arrays in order to keep track of the minimum.
// Brute force
Implementation 2
Not faster, just more correct. The question asks for the smallest non-negative difference. Meaning if it is negative, then we just simply just frame it the other way around, so abs should work.
Implementation 3
Actually faster. If we sort both arrays, which takes O(nlogn) - already puts us at an advantage, because we'll now have a clear direction to navigate ourselves. The key in this problem was know that if the current element in array 1 was larger than the element in the second array, then that means if we increment array 1, the next element would be larger, and so its difference with array 2 would also be larger. So if we increment the element in array 2, that element would be larger than its previous and its difference would smaller than the previous.
Last updated