Remove duplicates from a sorted array in place
Two pointers moving the same way. Read scans every element; write marks the end of the kept prefix. When read finds something new, copy it back to write and advance. O(n) time, O(1) extra space — and the function returns a length, because nothing was reallocated.
Overview
Why sorted matters
Duplicates in a sorted array are adjacent, so "have I seen this before?" collapses to "is it the same as the last one I kept?" — one comparison, no set, no memory.
On unsorted input this does not work and you need a set, which costs O(n) space, or a sort first, which costs O(n log n) time. Say which assumption you are relying on.
Step through it
What to watch
writeonly advances on a genuinely new value.- The comparison is against the last kept element, not the previous one read.
- The tail is left as stale data — that is why a length is returned.
Say this out loud
"Fast and slow pointers. Read scans, write marks the end of the deduped prefix, and I copy back only when the value differs from the last kept one. O(n) time, O(1) space, and I return the length because the tail is stale."