219. Cotains Duplicate II
🟩 Easy
Given an integer array nums
and an integer k
, return true
if there are two distinct indices i
and j
in the array such that nums[i] == nums[j]
and abs(i - j) <= k
.
Example 1
Input: nums = [1,2,3,1], k = 3 Output: true
Example 2
Input: nums = [1,0,1,1], k = 1 Output: true
Example 3
Input: nums = [1,2,3,1,2,3], k = 2 Output: false
Constraints
1 <= nums.length <= 10^5
-10^9 <= nums[i] <= 10^9
0 <= k <= 10^5
Solution
My Solution (Hash Map with Index)
Optimal Solution 1 (Sliding Window)
Optimal Solution 2 (Two Pointers)
Approach Analysis
This problem demonstrates different approaches to handle window constraints:
Hash Map with Index (Your Solution):
Store value-index pairs
Check distance on duplicates
Early termination
Space-time balanced
Sliding Window:
Maintain k-sized window
Remove old elements
Check current window
Memory efficient
Two Pointers:
Direct index comparison
Limited search range
No extra space
Simple implementation
Visualization of Approaches
Hash Map Process (Your Solution)
Sliding Window Process
Two Pointers Process
Complexity Analysis
Hash Map Solution (Your Solution)
Time: O(n)
Single pass through array
O(1) map operations
Early termination
Space: O(n)
Stores all unique indices
Map overhead
Worst case: all unique
Sliding Window Solution
Time: O(n)
Linear scan
Window operations O(1)
Delete operations O(1)
Space: O(k)
Fixed window size
Maximum k elements
More memory efficient
Two Pointers Solution
Time: O(n*k)
Nested loops
k comparisons per element
No early termination
Space: O(1)
No extra storage
Only pointers
Most space efficient
Why Solutions Work
Hash Map Logic:
Track last seen index
Quick distance check
Update on duplicates
Maintain history
Sliding Window:
Fixed size window
Remove old elements
Contains duplicates
Distance guaranteed
Two Pointers:
Direct comparison
Limited range check
No extra storage
Simple but slower
When to Use
Hash Map When:
Memory available
Quick lookups needed
Early termination helps
Index tracking important
Sliding Window When:
Memory constrained
Fixed window size
Stream processing
Order matters
Two Pointers When:
No extra space allowed
k is small
Simple code preferred
Memory critical
Common Patterns & Applications
Related Problems:
Contains Duplicate III
Sliding Window Maximum
Find All Anagrams
Longest Substring
Key Techniques:
Sliding window
Hash map tracking
Two pointers
Distance constraints
Interview Tips
Solution Highlights:
Multiple approaches
Space-time tradeoffs
Early termination
Window management
Common Pitfalls:
Off-by-one errors
Window boundaries
Index calculations
Memory management
Testing Strategy:
k = 0 case
k > array length
Duplicate at distance k
No duplicates
All duplicates
Follow-up Questions:
Streaming data?
Limited memory?
Parallel processing?
Different distance metrics?
Last updated
Was this helpful?