The Runtime Theory
easyleetcode#array#two-pointers

Remove Duplicates from Sorted Array

Remove duplicates from a sorted array in place using two pointers, returning the count of unique elements in O(n) time.

The Runtime Theory Team1 min read
Solve it

solving happens on the judge — come back and mark it done

Sample cases

in[1,1,2]

out2

in[0,0,1,1,1,2,2,3,3,4]

out5

in[5,5,5]

out1

The machine must remove duplicates in place from a sorted array and return the new length k; the first k slots must hold the unique values, in order. The insight: since the array is sorted, a slow pointer marks where the next unique value belongs, and a fast pointer finds it. Write, don't delete — overwriting is cheaper than shifting.

python
def remove_duplicates(nums):
    if not nums:
        return 0
    write = 1
    for read in range(1, len(nums)):
        if nums[read] != nums[read - 1]:
            nums[write] = nums[read]
            write += 1
    return write

Steps: (1) keep a write pointer starting at 1, (2) scan with a read pointer, (3) when a value differs from its predecessor, copy it to the write position and advance.

Time is O(n), one pass. Space is O(1) — in place, no auxiliary array.

Trickiest edge cases: an empty array returns 0 before any pointer moves. A single element returns 1. All-identical input like [5,5,5] returns 1 with the first slot unchanged. The comparison is against nums[read - 1] (the previous element), not against the last written value — both work on sorted input, but the read-1 variant is immune to write/read skew bugs.

More practice in this topic

One dispatch a week

The trace behind each problem, the tradeoff that explains it, and one technical dispatch per week — no noise.

One technical dispatch per week. No noise.