Overview
Curated: · Written: · Reviewed:
Two Pointers
In one line
Two indices walk one sequence, converging from the ends, running in the same direction, or moving in lockstep at different speeds, so each move permanently discards candidates and the scan is O(n) instead of O(n^2). Reach for it when the input is sorted or has a positional order that lets one move rule out a whole class of answers.
Key definitions
- Elimination argument: the reason a move is safe, namely that the candidates it discards can never be the answer.
- Invariant: a statement of what the untouched region cannot contain. State it before writing the loop.
- Converging pointers: lo starts at 0 and hi at n-1 on a sorted array, and they move toward each other.
- Same-direction pointers: a read pointer that always advances and a write pointer that advances only when an element is kept.
- Fast and slow pointers: one step versus two per iteration. A meeting proves a cycle exists but does not locate its entry.
- Running maximum: the tallest wall seen so far from one side. Trapping-water uses it in place of the current height.
Formulas and complexity
The sort dominates on unsorted input. The walk makes at most pointer moves because neither pointer is ever assigned backwards. Extra space is O(1): two or three indices. A hash index for the same pair search needs O(n) memory. Fixing one element of a triple gives , not . Answering q sorted queries against m sorted elements by binary search costs ; one merge walk costs .
How it works
Converging pair search: if a[lo] + a[hi] is below the target, no pair using this lo can work with a smaller hi, so lo advances. If it is above, hi retreats. Each move deletes a row or column of the pair matrix.
Same-direction compaction: the read pointer moves every iteration and the write pointer moves only when the element is kept, so a[0:write] always holds the kept elements in order. Return the length. Elements past it are unspecified.
Cycle detection: inside a cycle the gap between fast and slow shrinks by one each step, so they meet. To find the entry, restart one pointer at the head and step both one at a time until they meet.
When to use and when not to
| Situation | Two pointers | Alternative |
|---|---|---|
| Sorted values, pair or triple sum | Yes: O(n), or O(n^2) for triples | Hash map if sorting is not allowed |
| Memory capped, streamed or memory-mapped data | Yes: O(1) extra | Hash index needs O(n) memory |
| Unsorted input | No, unless you pay for the sort | Hash map: O(n) time and space |
| One lookup in sorted data | Overkill | Binary search: O(log n) |
| Many sorted queries | Yes: one merge walk | Repeated binary search |
| Original indices must be reported | Sort carrying indices, or use a hash map | Hash map keeps positions |
Traps interviewers probe
- Running the sorted walk on unsorted input. Fix: sort with original indices or use a hash map, and quote the sort cost.
- Moving both pointers on a mismatch, which skips valid pairs. Fix: advance only the pointer the inequality implicates.
- Leaving duplicates after a match, so results repeat or blow up on runs of equal values. Fix: skip equal values at lo and hi at the point of advancing.
- Treating Floyd's meeting point as the cycle entry. Fix: run the second phase one step at a time from the head.
- Off-by-one loops. Use lo < hi when a single element is not admissible and lo <= hi when it is. For the middle of an even list,
while fast and fast.nextreturns the second middle andwhile fast.next and fast.next.nextreturns the first.
Interview tips
Open by naming the ordering and the invariant in one sentence, then give the complexity with the sort included.
Follow-ups to expect: why not hashing (memory, and whether output must be ordered); why the merge uses <= (stability); why in-place partition loses relative order (the swap moves an element across the others); why container-with-most-water always moves the shorter side (area is bounded by the shorter side and the width only shrinks); why trapping-water uses running maxima (the other side is already known to be at least as tall); why sorting mutates a caller's list (use sorted when mutation is outside the contract); why the Dutch-flag mid pointer stays put after a swap with high (the element just brought in is unexamined).
30-second answer: "The input is sorted, so each move discards a whole row of the pair matrix. When the sum is below target, only a larger left value can help, so lo advances. That is two indices and constant extra space. The sort costs O(n log n), so the total is O(n log n). The walk itself is linear because each pointer only moves one way, at most 2n moves. I skip duplicates as I advance. If the input were unsorted, I would use a hash map instead."
Feedback on this overview
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.