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.