Contains Duplicate II (LeetCode 219): Solution and Explanation
Given an integer array and a distance k, decide whether some value appears twice at positions i and j with i not equal to j and abs(i - j) <= k. In other words, look for a repeated value whose two occurrences are close together.
Watch it run step by step
Try your own input and write the code →Intuition
The brute force version compares every element with each of the next k elements. That is correct, but when k is large it degrades to comparing every pair, which is O(n²) for arrays of up to 100,000 elements. You need a way to answer "have I seen this value recently?" without rescanning.
Think about which earlier occurrence actually matters. If a value appeared at indices 2, 5 and 9, and you are now at index 11, the closest previous occurrence is index 9. If 11 - 9 is greater than k, then 11 - 5 and 11 - 2 are even greater, so the older positions can never help. That means for every value you only need to remember the most recent index where you saw it.
A hash map from value to its last index captures exactly that. As you scan left to right, look up the current value. If it is there and the gap to the stored index is at most k, you have found a nearby duplicate. Whether or not it was close enough, overwrite the stored index with the current one, because the current position is now the most recent and therefore the most useful for future elements. Each element costs one lookup and one write, so the scan is linear.
Approach: Hash map of last-seen indices
- Create an empty dictionary
seenthat maps each value to the last index where it appeared. - Iterate through
numswithenumerate, getting indexiand valuenum. - If
numis inseenandi - seen[num] <= k, return True right away. - Otherwise set
seen[num] = i, replacing any older index so the map always holds the closest previous occurrence. - If the loop finishes without finding a close pair, return False.
Step-by-step example
nums = [1, 2, 3, 1, 2, 3], k = 2
- Indices 0, 1 and 2 hold new values, so
seenbecomes {1: 0, 2: 1, 3: 2}. - At index 3 the value 1 was last seen at 0. The gap is 3, which is greater than 2, so update
seen[1] = 3. - At index 4 the value 2 was last seen at 1. The gap is 3, so update
seen[2] = 4. - At index 5 the value 3 was last seen at 2. The gap is 3 again, so update
seen[3] = 5. - The loop ends and the function returns False. With
k = 3instead, index 3 would see a gap of exactly 3 and return True.
Code: Python, Java, C++
1class Solution:
2 def containsNearbyDuplicate(self, nums: List[int], k: int) -> bool:
3 seen = {}
4 for i, num in enumerate(nums):
5 if num in seen and i - seen[num] <= k:
6 return True
7 seen[num] = i
8 return False1class Solution {
2 public boolean containsNearbyDuplicate(int[] nums, int k) {
3 Map<Integer, Integer> map = new HashMap<>();
4 for (int i = 0; i < nums.length; i++) {
5 if (map.containsKey(nums[i]) && i - map.get(nums[i]) <= k) {
6 return true;
7 }
8 map.put(nums[i], i);
9 }
10 return false;
11 }
12}1class Solution {
2public:
3 bool containsNearbyDuplicate(vector<int>& nums, int k) {
4 unordered_map<int, int> seen;
5 for (int i = 0; i < nums.size(); i++) {
6 if (seen.count(nums[i]) && i - seen[nums[i]] <= k) {
7 return true;
8 }
9 seen[nums[i]] = i;
10 }
11 return false;
12 }
13};Time and space complexity
O(n)
Each of the n elements triggers one dictionary lookup and one assignment, both constant time on average.
O(n)
In the worst case every value is distinct and the dictionary stores n entries. The sliding window set alternative below caps this at O(min(n, k)).
Other approaches
Sliding window hash set (time O(n), space O(min(n, k)))
Maintain a set of the last k values. For each element, return True if it is already in the set; otherwise add it, and if the set grows past k elements, remove nums[i - k]. This bounds memory by k, which helps when k is much smaller than n.
Brute force over the next k elements (time O(n × min(n, k)), space O(1))
For each index, compare it with up to k following elements. It needs no extra memory and is fine when k is tiny, but it degrades to quadratic time when k is close to n.
Common mistakes
- Using
< kinstead of<= k. A gap of exactlykcounts as nearby. - Storing only the first index of each value and never updating it. Later duplicates can then look too far apart even though a closer earlier occurrence exists.
- In the window set version, removing the old element before checking the new one, or removing
nums[i - k - 1]instead ofnums[i - k], which shifts the window by one. - Returning True for
k = 0. Two distinct indices always differ by at least 1, so withk = 0the answer is always False.
Frequently asked questions
Why only store the most recent index for each value?
Any older index is farther from the current position, so if the most recent one is too far, every older one is too. Keeping only the latest index gives the best chance of a match at the lowest memory cost.
Hash map or sliding window set for Contains Duplicate II?
Both run in O(n). The set version limits memory to about k entries, while the map version is a little simpler to write. Choose the set when k is small relative to the array.
How is this different from Contains Duplicate III?
Part III also allows the values to differ by up to some threshold, not just be equal. That needs an ordered set or bucketing by value range, rather than a plain hash lookup.