Skip to main content
Easy Two Pointers High frequency

Remove Duplicates from Sorted Array

Open on LeetCode

Approach Summary

Slow pointer is the write head. Fast pointer scans; write only when a new unique element is found.

Full Solution & Approach

The array is sorted, so every duplicate of a value sits directly next to the original. Use a write pointer that tracks where the next unique element should be placed and a read pointer that scans the array. For every element, if it differs from the previous element written, copy it to the write position and advance the write pointer; otherwise skip it. Since the input is sorted, "different from the previous written element" is exactly the condition for being a new unique value. At the end the first k positions hold the unique elements in order and k is the answer. This is the in-place filter pattern: a read pointer always advances, a write pointer only advances when something should be kept. The same skeleton removes zeroes, removes elements by value, and compresses in place.

A single pass where each element is read once and written at most once — O(n) time. No extra arrays — O(1) space.

Solution Code

Solution

def remove_duplicates(nums: list[int]) -> int:
    write = 0
    for read in range(len(nums)):
        if write == 0 or nums[read] != nums[write - 1]:
            nums[write] = nums[read]
            write += 1
    return write

Edge Cases to Watch

  • Empty array — return 0
  • All elements identical — k is 1
  • No duplicates — k equals the array length and no writes shift anything
  • Single element — return 1

How to Recognize This Pattern

  • In-place deduplication of sorted array

Complexity Analysis

Time Complexity

O(n)

Space Complexity

O(1)

Tags

Array Two Pointers

This site is free. If these guides are helping your prep, consider buying me a coffee. ☕

Support →
Buy me a coffee