You are given an integer array nums and an integer k, return true if there are two distinct indices i and j in the array such that nums[i] == nums[j] and abs(i - j) <= k, otherwise return false.
Example 1:
Input: nums = [1,2,3,1], k = 3
Output: trueExample 2:
Input: nums = [2,1,2], k = 1
Output: falseConstraints:
1 <= nums.length <= 100,000-1,000,000,000 <= nums[i] <= 1,000,000,0000 <= k <= 100,000The simplest approach is to check every pair of elements. For each element, we look at all elements within distance k and check if any of them are equal. This guarantees finding a duplicate if one exists within the required distance.
L from 0 to n-1.L, iterate through index R from L+1 to min(n-1, L+k).nums[L] == nums[R], return true.false.Where is the size of the array and is the maximum distance between two equal numbers.
Instead of checking all pairs, we can store the most recent index of each value in a hash map. When we encounter a value, we check if it appeared before and if the distance to its last occurrence is within k. This gives us O(1) lookup time for duplicates.
i.nums[i] exists in the map and i - map[nums[i]] <= k, return true.map[nums[i]] = i (store the current index).false.Where is the size of the array and is the maximum distance between two equal numbers.
We only need to check for duplicates within a sliding window of size k. Using a hash set, we maintain exactly the elements in the current window. If a new element already exists in the set, we found a duplicate within distance k. We slide the window by removing the leftmost element when the window exceeds size k.
L and R, with R iterating through the array.R - L exceeds k, remove nums[L] from the set and increment L.nums[R] is already in the set, return true.nums[R] to the set.false.Where is the size of the array and is the maximum distance between two equal numbers.
The condition requires the distance to be "at most k", meaning abs(i - j) <= k, not < k. Using strict inequality will miss valid pairs that are exactly k positions apart.
# Wrong: Using strict inequality
if nums[i] in mp and i - mp[nums[i]] < k: # Misses distance == k
# Correct: Use <= for "at most k"
if nums[i] in mp and i - mp[nums[i]] <= k:The hash map only needs to store the most recent index for each value. Storing all indices wastes memory and complicates the logic. Since we iterate left to right, we only care about the closest previous occurrence.