Skip to content

Instantly share code, notes, and snippets.

@andersonleite
Last active July 17, 2019 00:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save andersonleite/ac6b77a75d3bed621166495e346ffd7d to your computer and use it in GitHub Desktop.
Save andersonleite/ac6b77a75d3bed621166495e346ffd7d to your computer and use it in GitHub Desktop.
Distinct indices
// Given an array of integers nums and an integer k, determine whether there are two distinct indices i and j in the array where nums[i] = nums[j] and the absolute difference between i and j is less than or equal to k.
// Example
// For nums = [0, 1, 2, 3, 5, 2] and k = 3, the output should be
// containsCloseNums(nums, k) = true.
// There are two 2s in nums, and the absolute difference between their positions is exactly 3.
// For nums = [0, 1, 2, 3, 5, 2] and k = 2, the output should be
// containsCloseNums(nums, k) = false.
// The absolute difference between the positions of the two 2s is 3, which is more than k.
function containsCloseNums(nums, k) {
let map = new Map()
for(let i=0; i < nums.length; i++){
if(map.get(nums[i])!==null && i - map.get(nums[i]) <= k){
return true
}
map.set(nums[i], i)
}
return false
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment