Skip to content

Instantly share code, notes, and snippets.

@toxi-kb
Created March 17, 2020 07:08
Show Gist options
  • Select an option

  • Save toxi-kb/859037d3c6cbe2736ca441837029edfc to your computer and use it in GitHub Desktop.

Select an option

Save toxi-kb/859037d3c6cbe2736ca441837029edfc to your computer and use it in GitHub Desktop.
function minimumDistances(numbers) {
const numberQuantity = numbers.length;
const firstOccurrences = {};
let minDistance = Infinity;
for (let idx = 0; idx < numberQuantity; idx += 1) {
const num = numbers[idx];
const firstOccurrenceIdx = firstOccurrences[num];
if (firstOccurrenceIdx === undefined) {
firstOccurrences[num] = idx;
} else if (idx - firstOccurrenceIdx < minDistance) {
minDistance = idx - firstOccurrenceIdx;
}
}
return minDistance !== Infinity ? minDistance : -1;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment