Smallest Difference
Smallest Difference
// O(nlog(n) + mlog(m)) time | O(1) space
function smallestDifference(arrayOne, arrayTwo) {
arrayOne.sort((a, b) => a - b);
arrayTwo.sort((a, b) => a - b);
let indexOne = 0;
let indexTwo = 0;
let smallest = Infinity;
let current = Infinity;
let smallestPair = [];
while (indexOne < arrayOne.length && indexTwo < arrayTwo.length) {
let firstNum = arrayOne[indexOne];
let secondNum = arrayTwo[indexTwo];
if (firstNum < secondNum) {
current = secondNum - firstNum;
indexOne++;
} else if (firstNum > secondNum) {
current = firstNum - secondNum;
indexTwo++;
} else {
return [firstNum, secondNum]
}
if (smallest > current) {
smallest = current;
smallestPair = [firstNum, secondNum]
}
}
return smallestPair
}
// Do not edit the line below.
exports.smallestDifference = smallestDifference;
Last updated