Skip to content

Instantly share code, notes, and snippets.

@abimaelmartell
Created March 13, 2021 00:23
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save abimaelmartell/82a335442934b22cb4bfea5943ba6e30 to your computer and use it in GitHub Desktop.
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.
/*
* 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