← back to stream

Two pointers

Two pointers is a technique that walks two indices through an array (or string) simultaneously, usually either converging from opposite ends or moving in the same direction at different speeds. It replaces an O(n²) nested loop with O(n) by using problem structure — the array is sorted, or the answer space is monotonic, so you can rule out entire regions by moving a pointer instead of re-checking. Classic uses: two-sum on a sorted array (move left pointer right if sum too low, right pointer left if too high), palindrome check (mirror-walk from both ends), merging two sorted arrays, removing duplicates in place, detecting cycles in a linked list (Floyd's tortoise and hare). It pairs well with sliding window — both are "don't recompute, update".