From e23bf45c7b4e0eb1e89ecccf1b337a3a2f5a1c28 Mon Sep 17 00:00:00 2001 From: TK Date: Mon, 1 Jan 2024 12:34:35 -0300 Subject: [PATCH] * --- .../smallest-difference.js | 25 +++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 coding_interviews/algoexpert/smallest-difference/smallest-difference.js diff --git a/coding_interviews/algoexpert/smallest-difference/smallest-difference.js b/coding_interviews/algoexpert/smallest-difference/smallest-difference.js new file mode 100644 index 0000000..a01eca2 --- /dev/null +++ b/coding_interviews/algoexpert/smallest-difference/smallest-difference.js @@ -0,0 +1,25 @@ +function smallestDifference(arrayOne, arrayTwo) { + let output = []; + let indexOne = 0; + let indexTwo = 0; + let smallestDistance = Infinity; + + arrayOne.sort((a, b) => a - b); + arrayTwo.sort((a, b) => a - b); + + while (indexOne < arrayOne.length && indexTwo < arrayTwo.length) { + let one = arrayOne[indexOne]; + let two = arrayTwo[indexTwo]; + let distance = Math.abs(one - two); + + if (distance < smallestDistance) { + smallestDistance = distance; + output = [one, two]; + } + + if (one < two) indexOne++; + else indexTwo++; + } + + return output; +}