All identical
Every element is the same. The write pointer never advances past 1, producing a single-element result. The read pointer scans the entire array without copying.
A library shelf holds books sorted by catalog number, but over the years duplicates have crept in. An assistant walks the shelf left to right, advancing a write marker only when a new title appears — each unique book slides into the write position while duplicates are simply passed over. After one pass the shelf is compacted: unique titles at the front, the write index reporting how many remain. O(n) time. O(1) space.
The write pointer starts at index 1 (the first element is always kept). For each read position, compare against the value at write − 1 — the last confirmed unique. If different, write it and advance; if the same, skip.
The array is sorted, so duplicates are always adjacent. A single forward pass with two pointers compacts unique values to the front.
Set write = 1. The first element is always unique, so we start scanning from index 1.
For each read from 1 to n − 1, compare nums[read] with nums[write − 1].
If nums[read] ≠ nums[write − 1], copy it to nums[write] and advance write.
After the scan, write equals the number of unique elements.
Understanding boundary behavior is as important as the main algorithm path.
Every element is the same. The write pointer never advances past 1, producing a single-element result. The read pointer scans the entire array without copying.
No duplicates exist. Every comparison succeeds, and the write pointer tracks the read pointer exactly — the array is unchanged.
Time: O(n) — single pass.
Space: O(1) — two pointers.