Contains Duplicate II
LeetCode 219 · Easy · solution, intuition & step-by-step walkthrough
Last-seen index map; compare distance.
This is how I solved Contains Duplicate II (LeetCode 219), an easy problem from the Fixed Window pattern. Below: the intuition, the approach step by step, my accepted Python code, animated test cases and a line-by-line debugger.
Intuition
Remember the last index of every value. When the same value shows up again, check whether the distance to its last occurrence is at most k.
Approach
- 1
For each index i and value num.
- 2
If num was seen and i − last ≤ k, return True.
- 3
Update the last index for num.
How I solved it
Last-index mapPythonO(n) time · O(n) space
class Solution:
def containsNearbyDuplicate(self, nums: List[int], k: int) -> bool:
seen = {}
for i,num in enumerate(nums):
if num in seen:
j = seen.get(num)
if abs(i-j)<=k:
return True
seen[num]=i
return FalseContains Duplicate II — FAQ
What is the intuition behind Contains Duplicate II?
Remember the last index of every value. When the same value shows up again, check whether the distance to its last occurrence is at most k.
How do you solve Contains Duplicate II (LeetCode 219)?
1. For each index i and value num. 2. If num was seen and i − last ≤ k, return True. 3. Update the last index for num.
What is the time and space complexity of Contains Duplicate II?
Time: O(n). Space: O(n). (Accepted approach: Last-index map.)
What are common mistakes in Contains Duplicate II?
Always update to the latest index — older ones are farther away.