Two Pointers
Walk an array from two positions to turn O(n^2) scans into O(n).
5 pages, free to read
- 1
Pointers from both ends
BeginnerStart one pointer at each end of a sorted array or string and move them toward each other, discarding a whole set of candidates with every step, so one O(n) pass replaces checking all pairs.
9 min read - 2
Fast & slow pointers
IntermediateMove one pointer one step and another two steps at a time: if there is a cycle the fast one laps the slow one, and if there is none the slow one ends at the middle when the fast one hits the end.
10 min read - 3
Read & write pointers (in-place)
BeginnerOne pointer reads every element while a second marks where the next kept element goes, so you filter or compact an array in place in a single O(n) pass.
8 min read - 4
Pair and triplet sums
IntermediateSort the array, fix one element, and find the rest with two pointers: two sum becomes O(n), three sum O(n^2), and duplicates are skipped by comparing neighbours.
11 min read - 5
Merging sorted sequences
BeginnerWalk two sorted sequences with one pointer each, always taking the smaller front element, to produce one sorted result in O(n + m).
9 min read