Topic 3 of 20
Two indices moving through data to replace nested loops with a single pass.
The two-pointer technique keeps two indices into a sequence and moves them according to a rule, turning many O(n²) pair searches into a single O(n) pass. There are two main shapes. Opposite ends: one pointer starts at the left, one at the right, and they move toward each other (palindromes, pair sums in a sorted array, container problems). Same direction: a fast "reader" scans every element while a slow "writer" marks where the next kept element goes (removing duplicates, moving zeroes, partitioning).
Two pointers usually needs some kind of order. If the input is not sorted, sorting it first (O(n log n)) often unlocks the technique, which is exactly how 3Sum and 4Sum reduce to repeated Two Sum. The key interview skill is proving why moving a pointer can never skip the answer. Practise saying that argument out loud.
This topic also prepares you for Sliding Window (two same-direction pointers with a condition) and for the fast & slow pointers used on linked lists.
The simplest opposite-ends scan, with character filtering.
Allows one deletion, so you learn to branch once and re-check; a Meta favourite.
In-place swap from both ends; the building block for reversal tricks.
Filling from the end avoids overwriting data; a standard in-place merge.
Introduces the reader/writer pointer pair.
Stable in-place partitioning with minimal writes.
Greedy matching with two pointers over two strings.
Largest values sit at the ends, so you fill the output from the back.
Sorted input turns Two Sum into an O(1)-space two-pointer scan.
Reduces k-sum to 2-sum and tests duplicate handling; asked constantly.
Same skeleton as 3Sum but optimising a distance instead of matching.
Generalises the k-sum reduction and overflow awareness.
The classic 'move the shorter side' proof; very frequently asked.
Three-way partitioning in one pass; also the core of 3-way quicksort.
Generalises read/write pointers to 'keep at most k copies'.
Pairs the heaviest with the lightest; a greedy argument in two-pointer form.
Reverse the whole string, then each word: an in-place classic.
Two pointers plus counting with powers of two; a strong Medium.
The most famous two-pointer Hard; also solvable with prefix maxima or a stack.