Contains Duplicate II (LeetCode 219): Solution and Explanation

Easy
Array
Hash Table
Sliding Window

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.

Variables
No variables to display
DepthFunction Call
Stack empty
0/0

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

  1. Create an empty dictionary seen that maps each value to the last index where it appeared.
  2. Iterate through nums with enumerate, getting index i and value num.
  3. If num is in seen and i - seen[num] <= k, return True right away.
  4. Otherwise set seen[num] = i, replacing any older index so the map always holds the closest previous occurrence.
  5. If the loop finishes without finding a close pair, return False.

Step-by-step example

nums = [1, 2, 3, 1, 2, 3], k = 2
  1. Indices 0, 1 and 2 hold new values, so seen becomes {1: 0, 2: 1, 3: 2}.
  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.
  3. At index 4 the value 2 was last seen at 1. The gap is 3, so update seen[2] = 4.
  4. At index 5 the value 3 was last seen at 2. The gap is 3 again, so update seen[3] = 5.
  5. The loop ends and the function returns False. With k = 3 instead, 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 False

Time and space complexity

Time

O(n)

Each of the n elements triggers one dictionary lookup and one assignment, both constant time on average.

Space

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 < k instead of <= k. A gap of exactly k counts 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 of nums[i - k], which shifts the window by one.
  • Returning True for k = 0. Two distinct indices always differ by at least 1, so with k = 0 the 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.