Remove Duplicates from Sorted Array
LeetCode 26 · Easy · solution, intuition & step-by-step walkthrough
Write pointer advances only on a new value.
This is how I solved Remove Duplicates from Sorted Array (LeetCode 26), an easy problem from the Two Pointers pattern. Below: the intuition, the approach step by step, my accepted Python code, animated test cases and a 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.
How I solved it
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 — FAQ
What is the intuition behind Remove Duplicates from Sorted Array?
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.
How do you solve 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.
What is the time and space complexity of Remove Duplicates from Sorted Array?
Time: O(n). Space: O(1). (Accepted approach: Read / write pointers.)
What are common mistakes in Remove Duplicates from Sorted Array?
Compare with nums[i−1] (the original neighbour), not with the write slot.