"When the brute force is 'compare every pair,' stop. Often two indices walking the array cleverly can do in one pass what nested loops do in n²."
The Core Move
The two-pointer technique keeps two indices moving through an array and uses their relationship to skip work that nested loops would repeat. There are two main flavors:
- Converging — one pointer at each end, walking toward the middle. Great for palindromes, pair-sum on a sorted array, reversing, "trap the most water."
- Same-direction (fast/slow) — both start at the front, one races ahead. Great for de-duping in place, partitioning, sliding things along.
The payoff is almost always the same: an O(n²) brute force collapses to O(n) time and O(1) space, because each pointer crosses the array at most once and you carry no extra structure.
Why It Works: Sorted Order Lets You Decide a Direction
Take "find two numbers that sum to a target" in a sorted array. Brute force checks all pairs: O(n²). With two pointers at the ends, look at their sum. Too small? The only way to grow it is to move the left pointer right (toward bigger values). Too big? Move the right pointer left. Each move rules out a whole set of pairs you never have to check. One pass, O(n). The sorted order is what tells you which pointer to move — that's the hidden engine.
The Tell
When should this technique flash in your mind? When you catch yourself about to write nested loops over one array, especially with words like "pair," "palindrome," "reverse," "both ends," "in place," or "sorted." That's the signal to ask: can two indices and a rule about how they move do this in one sweep? We'll meet its close cousin — the sliding window — in the very next lesson.