Skip to content

Instantly share code, notes, and snippets.

@Shaddyjr
Created June 6, 2022 05:06
Show Gist options
  • Select an option

  • Save Shaddyjr/e0ebce72b94fee5e7ad164f6c2b29369 to your computer and use it in GitHub Desktop.

Select an option

Save Shaddyjr/e0ebce72b94fee5e7ad164f6c2b29369 to your computer and use it in GitHub Desktop.
// source: https://www.hackerrank.com/challenges/minimum-distances/problem
// video: https://youtu.be/gKp8Aq9mm9E
function minimumDistances(a) {
// stores each unique value as a key with a value of last index
const val_last_i = {}
let min_distance = Infinity;
// loop through array and populate val_last_i
for(let i = 0; i < a.length; i++){ // O(n)
const val = a[i]
if (val in val_last_i){
// val is a duplicate...
// calculate distance from last i
const distance = i - val_last_i[val]
// assign min distances when appropriate
if (distance < min_distance){
min_distance = distance
}
}
val_last_i[val] = i
}
// if each value is unique, there are no duplicates
// this is indicated by min_distance still being Infinity
if (min_distance == Infinity){
return -1
}
return min_distance // Total Time Complexity: O(n)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment