The problem

Given a sorted array, modify it in place so that each element appears at most once and return the new length.

1
2
3
4
5
6
7
8
9
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

This is the read/write variant of two pointers — one pointer scans the input while the other tracks where to write the next unique element.

Where to next?

You’ve finished a complete worked example using the two-pointer pattern. Continue to the next course in this track to see how the same idea generalizes to sliding windows.

Saved locally to your browser.