LeetCode 219: Contains Duplicate II is an Easy hashmap problem. This Python walkthrough develops a last-index tracking solution, ties every code decision to a concrete invariant, and includes the regression check used before publication.
This independent guide paraphrases the task rather than reproducing LeetCode’s prompt. Use the official page for the exact statement, examples, constraints, and submission runner.
| Difficulty | Easy |
|---|---|
| Topic | Hashmap |
| Reusable pattern | last-index tracking |
| Complexity | O(n) time and O(n) space |
Recognizing the pattern
A hash table converts a repeated search for prior information into an average constant-time lookup.
For this problem specifically, record the most recent index of each value and test whether the distance to the current occurrence is within k. The invariant worth writing beside the code is: The map holds the closest possible prior occurrence for every value.
Step-by-step algorithm
- Identify the input state consumed by
containsNearbyDuplicate(nums, k)and initialize the data required by the last-index tracking pattern. - Record the most recent index of each value and test whether the distance to the current occurrence is within k.
- After each update, verify the page’s central invariant: The map holds the closest possible prior occurrence for every value.
- Finish only after the boundary behavior is covered: k equal to zero can never match distinct indices.
Python solution
class Solution:
def containsNearbyDuplicate(self, nums, k):
last = {}
for i, value in enumerate(nums):
if value in last and i - last[value] <= k: return True
last[value] = i
return FalseReading the implementation
The main entry point is containsNearbyDuplicate(nums, k). The named working state includes last; those variables make the last-index tracking state visible instead of hiding it in incidental control flow.
A single main loop advances the algorithm, which is the key reason the traversal does not revisit already resolved input unnecessarily. In concrete terms, record the most recent index of each value and test whether the distance to the current occurrence is within k.
Correctness argument
Initialization. The data structure starts with exactly the information known before any input element is processed.
Preservation. Record the most recent index of each value and test whether the distance to the current occurrence is within k. Each update records the current item without invalidating earlier decisions; consequently, the map holds the closest possible prior occurrence for every value.
Termination. The traversal consumes a finite input or finite state space. At the end, the invariant covers the complete input, which is precisely the condition required for the returned result.
Complexity and trade-offs
O(n) time and O(n) space. The auxiliary-space figure excludes the returned output unless the output itself is the structure being built.
Sorting may reduce implementation state and reveal ordering, but it can lose original positions and normally costs O(n log n). That comparison is useful in an interview because it explains why the final implementation is preferable, not merely that it passes.
Regression check
The published implementation belongs to a 100-problem suite that is compiled and exercised behaviorally before deployment.
One reference assertion from that suite is shown below. It targets the normal path while the edge conditions in the next section cover the failure-prone boundaries.
assert Solution().containsNearbyDuplicate([1,2,3,1],3)Common mistakes and edge cases
- Problem-specific boundary: k equal to zero can never match distinct indices.
- Pattern-level pitfall: Choose whether to look up before inserting: inserting too early can accidentally match an element with itself.
- Invariant check: after every update, confirm that the map holds the closest possible prior occurrence for every value.
Interview review checklist
- Explain why last-index tracking matches the structure of this input.
- State the invariant in one sentence before tracing code: The map holds the closest possible prior occurrence for every value.
- Derive O(n) time and O(n) space from how many times each element or state is visited.
- Test the boundary explicitly: k equal to zero can never match distinct indices.
Browse the searchable 100 LeetCode Python Solutions hub. Previous: 202. Happy Number · Next: 128. Longest Consecutive Sequence