
Leetcode Problem 219: Contains Duplicate II
Given an integer array nums and an integer k, return true if there exist two distinct indices i and j such that nums[i] == nums[j] and the absolute difference |i - j| is at most k.
Constraints:
k is a non-negative integer up to 100,000.function containsNearbyDuplicate(nums: number[], k: number): boolean {
let previousNumbersWithIndex = new Map<number, number>()
for (let i = 0; i < nums.length; i++) {
if (previousNumbersWithIndex.has(nums[i]) && Math.abs(i - previousNumbersWithIndex.get(nums[i])!) <= k) {
return true
}
previousNumbersWithIndex.set(nums[i], i)
}
return false
};
console.log(containsNearbyDuplicate([1,2,3,1], 3))