Two Pointers
01 / The shared mechanism
Two indices moving over the same sequence to maintain an invariant — the move rule changes per sub-pattern, but the mechanism is shared.
02 / The one-sentence essence
When the input is sorted and the answer is a pair satisfying a relation, place pointers at both ends and move whichever side is wrong — each move is forced by the comparison.
Problemfind i, j with arr[i] + arr[j] = targetInput[1, 2, 4, 7, 11, 15]target9
10
21
42
73
114
155
Sorted input, target 9. Place left at the start and right at the end.
step
0 / 8
L · R
—
arr[L] + arr[R]
—
vs target
—
0 / 8
03 / The pattern signature
# two indices over one sorted sequenceleft ← 0right ← n − 1while left < right:// compare and decide which side to moveif arr[left] + arr[right] = target:return (left, right)elif sum < target:left++ // need a larger sumelse:right-- // need a smaller sum
04 / When to recognize this pattern
"sorted"
The input is already sorted, or you can sort it cheaply. Sortedness is what makes each move definite.
"pair"
The answer involves exactly two elements — a sum, a difference, a match.
"palindrome / mirror"
The data has a symmetric structure to verify, like comparing characters from both ends inward.
"closest to"
You're minimizing distance rather than matching exactly — track the best pair as you converge.
05 / Common pitfalls
i.
Reaching for it on unsorted data.
Without an ordering, moving a pointer doesn't monotonically change the candidate. Sort first, or this is the wrong tool.
ii.
Off-by-one on
while left < right.Use
< when a pair requires two distinct indices; use <= only when the same index can satisfy the relation alone (rare).iii.
Forgetting to advance past duplicates.
For problems like 3Sum, after a hit you may need to skip equal neighbors on both sides so the next iteration doesn't emit the same pair twice.
06 / Go practice — on LeetCode
Four problems, ordered by difficulty. The first three demand sortedness; the fourth tests the pattern on a sortable input.
— / When to use which
converging
Use when the array is sorted and the answer is a pair.
two-sum · palindrome · container
fast / slow
Use for in-place modification or cycle detection.
remove-dupes · linked-list cycles
sliding window
Use when the condition is about a contiguous chunk.
longest/shortest · at-most-k