Two Pointers · Sorted array

Remove Duplicates Visualizer

What is Remove Duplicates

The array is sorted. Compact it so the unique values form a prefix, and return how many unique values there are. A slow pointer writes the next new value. A fast pointer scans forward. The practice tests ask only for that count.

1 1 2
2

Approach

A setA set also counts distinct values. The in-place walk shows why sorting makes the job a single pass.
Write only when the value changesBecause the array is sorted, duplicates are neighbors. Keep a value when it differs from the last one written.

Interactive solution

The unique prefix growing behind the fast pointer
if the array is empty: return 0
write = 1
for fast in range(1, n):
if a[fast] != a[write - 1]: copy it and write += 1
else: skip the duplicate
return write
Step 0/0 Answer —

The finished picture is on screen when the page opens. Next and Play start again from the first step.

Complexity

PieceCostWhy
TimeO(n)Each index is read once.
MemoryO(1)The unique values overwrite the front of the same array.

Implementation

def unique_count(a):
    if not a:
        return 0
    w = 1
    for r in range(1, len(a)):
        if a[r] != a[w - 1]:
            a[w] = a[r]
            w += 1
    return w