0
0
DSA Pythonprogramming

Remove Duplicates from Sorted Array Two Pointer in DSA Python

Choose your learning style9 modes available
Mental Model
Use two pointers to overwrite duplicates in a sorted array, keeping only unique elements at the front.
Analogy: Imagine sorting your books on a shelf and removing extra copies by sliding unique books forward, ignoring repeats behind.
Array: [1, 1, 2, 2, 3, 4, 4]
Pointers: i ↑ j ↑
Initially both at start, i marks last unique, j scans ahead
Dry Run Walkthrough
Input: array: [1, 1, 2, 2, 3]
Goal: Remove duplicates so array starts with unique elements only
Step 1: Start with i=0 (first unique), j=1 scanning next element
[1 (i), 1 (j), 2, 2, 3]
Why: We compare j to i to find new unique elements
Step 2: j=1 equals i=0 value (1), so skip duplicate, move j forward
[1 (i), 1, 2 (j), 2, 3]
Why: Duplicate found, do not move i, just advance j
Step 3: j=2 value (2) differs from i=0 value (1), increment i and copy j's value to i
[1, 2 (i), 2 (j), 2, 3]
Why: Found new unique, move i forward and update array
Step 4: j=3 value (2) equals i=1 value (2), skip duplicate, move j forward
[1, 2 (i), 2, 2 (j), 3]
Why: Duplicate again, only advance j
Step 5: j=4 value (3) differs from i=1 value (2), increment i and copy j's value
[1, 2, 3 (i), 2, 3 (j)]
Why: New unique found, move i and update array
Result:
Final array start: [1, 2, 3] with length 3
Annotated Code
DSA Python
from typing import List

class Solution:
    def removeDuplicates(self, nums: List[int]) -> int:
        if not nums:
            return 0
        i = 0  # last unique element index
        for j in range(1, len(nums)):
            if nums[j] != nums[i]:
                i += 1
                nums[i] = nums[j]  # overwrite duplicate
        return i + 1

# Driver code
nums = [1, 1, 2, 2, 3]
sol = Solution()
length = sol.removeDuplicates(nums)
print("Unique length:", length)
print("Array after removing duplicates:", nums[:length])
if not nums:
handle empty array edge case
i = 0 # last unique element index
initialize pointer i to track last unique element
for j in range(1, len(nums)):
j scans through array from second element
if nums[j] != nums[i]:
check if current element is new unique
i += 1
move i forward to next unique position
nums[i] = nums[j] # overwrite duplicate
overwrite duplicate with new unique element
return i + 1
return count of unique elements
OutputSuccess
Unique length: 3 Array after removing duplicates: [1, 2, 3]
Complexity Analysis
Time: O(n) because we scan the array once with pointer j
Space: O(1) because we modify the array in place without extra space
vs Alternative: Compared to creating a new array for uniques (O(n) space), this uses constant space by overwriting duplicates
Edge Cases
empty array
returns 0 immediately
DSA Python
if not nums:
array with all duplicates
returns 1 with first element only
DSA Python
if nums[j] != nums[i]:
array with no duplicates
returns original length, array unchanged
DSA Python
if nums[j] != nums[i]:
When to Use This Pattern
When you see a sorted array and need to remove duplicates in place, use two pointers to overwrite duplicates efficiently.
Common Mistakes
Mistake: Starting i pointer at 1 instead of 0 causes index errors or misses first element
Fix: Initialize i to 0 to mark the first unique element
Mistake: Copying nums[j] to nums[i] without incrementing i leads to overwriting same position
Fix: Increment i before copying to ensure unique elements are placed correctly
Summary
Removes duplicates from a sorted array by overwriting duplicates with unique elements using two pointers.
Use when you want to remove duplicates in place without extra space.
The key is to keep one pointer for the last unique element and another to scan ahead for new uniques.