Remove Duplicates from Sorted Array II
LeetCode 80 · মাঝারি · সমাধান, intuition ও ধাপে ধাপে ওয়াকথ্রু
Keep nums[i] unless it equals nums[insert_index − 2].
আমি Remove Duplicates from Sorted Array II (LeetCode 80) এভাবে সমাধান করেছি — Two Pointers প্যাটার্নের একটি মাঝারি প্রবলেম। নিচে: intuition, ধাপে ধাপে approach, আমার accepted Python কোড, animated test cases আর line-by-line debugger।
নিচের বিবরণ ইংরেজিতে।
Intuition
Allow each value at most twice: compare the incoming element with the one two slots behind the write position. If they're equal, a third copy would appear, so skip it.
Approach
- 1
The first two elements are always kept; insert_index = 2.
- 2
For each later element, skip it if it matches nums[insert_index − 2].
- 3
Otherwise write it and advance.
- 4
Return insert_index.
আমি কীভাবে সমাধান করেছি
Write pointer, look back twoPythonO(n) time · O(1) space
class Solution:
def removeDuplicates(self, nums: List[int]) -> int:
insert_index=2
for i in range(2,len(nums)):
if nums[i]==nums[insert_index-2]:
continue
nums[insert_index]=nums[i]
insert_index+=1
return insert_indexRemove Duplicates from Sorted Array II — সাধারণ প্রশ্ন
Remove Duplicates from Sorted Array II-এর পেছনে intuition কী?
Allow each value at most twice: compare the incoming element with the one two slots behind the write position. If they're equal, a third copy would appear, so skip it.
Remove Duplicates from Sorted Array II (LeetCode 80) কীভাবে সমাধান করবেন?
1. The first two elements are always kept; insert_index = 2. 2. For each later element, skip it if it matches nums[insert_index − 2]. 3. Otherwise write it and advance. 4. Return insert_index.
Remove Duplicates from Sorted Array II-এর time আর space complexity কত?
Time: O(n)। Space: O(1)। (Accepted approach: Write pointer, look back two।)
Remove Duplicates from Sorted Array II-এ সাধারণ ভুলগুলো কী?
Compare against the write area, not the read area — that's what limits copies to two.