Command Palette

Search for a command to run...

← All patterns

Pattern · Pointers & Windows

Two Pointers: Read and Write

A fast pointer reads every element and a slow pointer marks where the next kept element should be written.

Time O(n) · Space O(1)

Taught in Module 6: Two Pointers

Think of it like this

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

Common versions

  • Remove duplicates from sorted array
  • Remove element
  • Move zeroes
  • Partition by a condition

Practice problems with this pattern

Related patterns