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.