- using a hashmap i check if a number exists in the map, if it doesnt then i store the index of the number in the map.
- if the number exists in the map the next time the number is seen in the array the absolute difference between the index of the previously stored number and its current duplicate is checked.
- if the difference is less than or equal to k i return true
-
Time complexity:O(N)
-
Space complexity:O(N)
function containsNearbyDuplicate(nums: number[], k: number): boolean {
let map = new Map()
for (let i = 0; i < nums.length; i++) {
if (map.has(nums[i]) && Math.abs(i - map.get(nums[i])) <= k) {
return true;
}
map.set(nums[i], i)
}
return false
};