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.