Given two arrays of integers, find the pair of values (one value in each array) with the smallest (non-negative) difference.
smallestand initialize it to
currentand initialize it to
Math.Max. This will keep track of the running difference which we can later compare with
smallestand determine which is the smallest difference so far.
jwhich will iterate over
arr2respectively. Also declare an array called
smallestPairwhich 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
secondNum - firstNumand increment
ivalue. We increment the
ivalue because since the array is sorted, we will get a higher number if we increment
iand ultimately there's a chance of a
smallerdifference coming up.
firstNum > secondNum, increment
firstNum - secondNum.
firstNum === secondNum. In this case, the difference is zero and that will be our answer.
current < smallest, set
current = smallestand
O(nlogn)because we sort the arrays.