Remove Duplicates from Sorted Array
LeetCode 26 · எளிது · தீர்வு, intuition & படிப்படியான வாக்த்ரூ
Write pointer advances only on a new value.
நான் Remove Duplicates from Sorted Array (LeetCode 26) ஐ இப்படித் தீர்த்தேன் — Two Pointers பேட்டர்னின் ஒரு எளிது பிராப்ளம். கீழே: intuition, படிப்படியான approach, என் accepted Python கோட், animated test cases மற்றும் line-by-line debugger.
கீழேயுள்ள விளக்கம் ஆங்கிலத்தில் உள்ளது.
Intuition
In a sorted array duplicates sit together. Keep a write index; copy an element forward only when it differs from the one before it. The first insert_index slots end up holding each value once.
Approach
- 1
insert_index starts at 1 (the first element is always kept).
- 2
Skip nums[i] if it equals nums[i−1].
- 3
Otherwise write it at insert_index and advance.
- 4
Return insert_index — the count of unique values.
நான் எப்படித் தீர்த்தேன்
Read / write pointersPythonO(n) time · O(1) space
class Solution:
def removeDuplicates(self, nums: List[int]) -> int:
insert_index=1
for i in range(1,len(nums)):
if nums[i]==nums[i-1]:
continue
nums[insert_index]=nums[i]
insert_index+=1
return insert_indexRemove Duplicates from Sorted Array — அடிக்கடி கேட்கப்படும் கேள்விகள்
Remove Duplicates from Sorted Array பின்னாலுள்ள intuition என்ன?
In a sorted array duplicates sit together. Keep a write index; copy an element forward only when it differs from the one before it. The first insert_index slots end up holding each value once.
Remove Duplicates from Sorted Array (LeetCode 26) ஐ எப்படித் தீர்ப்பது?
1. insert_index starts at 1 (the first element is always kept). 2. Skip nums[i] if it equals nums[i−1]. 3. Otherwise write it at insert_index and advance. 4. Return insert_index — the count of unique values.
Remove Duplicates from Sorted Array இன் time மற்றும் space complexity என்ன?
Time: O(n). Space: O(1). (Accepted approach: Read / write pointers.)
Remove Duplicates from Sorted Array இல் பொதுவான தவறுகள் என்ன?
Compare with nums[i−1] (the original neighbour), not with the write slot.