Sorting mail at a desk: your right hand picks up each letter, your left hand only moves forward when you keep one.
Clues that point here
→ Remove or move elements in place
→ "Return the new length"
→ Remove duplicates from a sorted array
→ Move zeroes to the end
→ O(1) extra space required
Not this pattern when
✕ The order of kept elements doesn't matter and swapping with the end is simpler
✕ You need a new array anyway
The template
A skeleton to adapt. The parts in comments are what changes from problem to problem.
Two Pointers: Read and Write · template
int write = 0;
for (int read = 0; read < arr.length; read++) {
if (keep(arr[read])) { // decide whether this element stays
arr[write] = arr[read];
write++;
}
}
return write; // new length; arr[0..write-1] holds the kept elements