Contains Duplicate II
Easy · Sliding Window · Explanation and code example
Hash Set
How it works
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.
Steps
- Create an empty hash set to represent the sliding window.
- Use two pointers
LandR, withRiterating through the array. - If the window size
R - Lexceedsk, removenums[L]from the set and incrementL. - If
nums[R]is already in the set, returntrue. - Add
nums[R]to the set. - If no duplicate is found, return
false.
Complexity
- Time complexity:
O(n) - Space complexity:
O(min(n, k))
Where
nis the size of the arraynumsandkis the maximum distance between two equal numbers.
Things to watch for
Off-by-One Error in Distance Check
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.
Storing All Indices Instead of Most Recent
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.
Python code example
from typing import List
class Solution:
def containsNearbyDuplicate(self, nums: List[int], k: int) -> bool:
window = set()
L = 0
for R in range(len(nums)):
if R - L > k:
window.remove(nums[L])
L += 1
if nums[R] in window:
return True
window.add(nums[R])
return False
C++ code example
class Solution {
public:
bool containsNearbyDuplicate(vector<int>& nums, int k) {
unordered_set<int> window;
int L = 0;
for (int R = 0; R < nums.size(); R++) {
if (R - L > k) {
window.erase(nums[L]);
L++;
}
if (window.find(nums[R]) != window.end()) {
return true;
}
window.insert(nums[R]);
}
return false;
}
};
Source and license
Adapted from NeetCode’s source · MIT license. Node types are supplied by LeetCode where needed.