Given two arrays of integers, find the pair of values (one value in each array) with the smallest (non-negative) difference.
O(nlogn)
complexity.smallest
and initialize it to Infinity
or Math.Max
.current
and initialize it to Infinity
or Math.Max
. This will keep track of the running difference which we can later compare with smallest
and determine which is the smallest difference so far.i
and j
which will iterate over arr1
and arr2
respectively. Also declare an array called smallestPair
which will keep track of the smallest difference pair.firstNum = arr[i]
and secondNum = [arr[j]
. Check which one is greater. If firstNum < secondNum
, Update the current
to be secondNum - firstNum
and increment i
value. We increment the i
value because since the array is sorted, we will get a higher number if we increment i
and ultimately there's a chance of a smaller
difference coming up.firstNum > secondNum
, increment j
and set current
equal to firstNum - secondNum
.firstNum === secondNum
. In this case, the difference is zero and that will be our answer.current
and smallest
. If current < smallest
, set current = smallest
and smallestPair
will be arr[i], arr[j]
.O(nlogn)
because we sort the arrays.