Created
March 13, 2021 00:23
-
-
Save abimaelmartell/82a335442934b22cb4bfea5943ba6e30 to your computer and use it in GitHub Desktop.
Given an array of distinct integers, determine the minimum absolute difference between any two elements. Return all element pairs with that minimal absolute difference in ascending order.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* Complete the 'closestNumbers' function below. | |
* | |
* The function accepts INTEGER_ARRAY numbers as parameter. | |
*/ | |
const closestNumbers = (numbers) => { | |
let result = []; | |
let minimalDistance = Infinity; | |
numbers.sort((a, b) => a - b); | |
for (let i = 0; i < numbers.length - 1; i++) { | |
const distance = Math.abs(numbers[i+1] - numbers[i]); | |
if (distance < minimalDistance) { | |
minimalDistance = distance; | |
result = []; | |
} | |
if (distance === minimalDistance) { | |
result.push([numbers[i], numbers[i + 1]]); | |
} | |
} | |
return result; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment