Contains Duplicate II
LeetCode 219 · आसान · समाधान, intuition और कदम-दर-कदम वॉकथ्रू
Last-seen index map; compare distance.
मैंने Contains Duplicate II (LeetCode 219) ऐसे हल किया — Fixed Window पैटर्न का एक आसान प्रॉब्लम। नीचे: intuition, कदम-दर-कदम approach, मेरा accepted Python कोड, animated test cases और 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.
मैंने कैसे हल किया
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 — अक्सर पूछे जाने वाले प्रश्न
Contains Duplicate II के पीछे 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.
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.
Contains Duplicate II की time और space complexity क्या है?
Time: O(n)। Space: O(n)। (Accepted approach: Last-index map।)
Contains Duplicate II में आम गलतियाँ क्या हैं?
Always update to the latest index — older ones are farther away.