The core idea
The two pointer technique keeps two indices into the same sequence and advances them according to a rule. Instead of comparing every pair with a nested loop, you move the pointers in a single coordinated sweep, often turning a quadratic scan into one linear pass.
When it applies
The technique shines when the data has structure you can exploit so that moving a pointer lets you safely skip work:
- Sorted arrays, where a comparison tells you which side to advance.
- In place rewrites, where one pointer reads and another writes.
- Linked structures, where pointers chase each other.
A simple example
To remove duplicates from a sorted array, a write pointer marks the next slot for a unique value while a read pointer scans ahead. When the read pointer finds a value different from the last kept one, you copy it to the write slot and advance both.
The key is that each pointer only ever moves forward, so the total number of moves is bounded by the length of the input.
Key idea
Two pointers replace a nested loop with one coordinated sweep, using the structure of the data to decide which pointer to advance and never moving either backward.