synopsis · Linear patterns · chapter 12
Two Pointers
10 cards, about a minute. Read them the night before an interview, or right after the chapter to lock it in.
- what it is
Two indices walk the data so every step throws away candidates for good: O(n) instead of the O(n²) all-pairs loop.
- use it when
Sorted array + pair or triplet sum, palindrome check, reverse in place, or keep/remove in place: think two pointers.
- template
Opposite ends:
l = 0, r = n - 1; while (l < r)— too small →l++, too big →r--. - template
Same direction:
readscans everything,writemarks the next free slot and moves only for keepers. - template
Two sorted inputs: one pointer each, take the smaller. Merging in place? Fill from the back so nothing is overwritten.
- cost
O(n) time, O(1) extra space. Sorting first adds O(n log n), still far better than O(n²).
- trap
l <= rpairs an element with itself. Pair problems usel < r. - trap
Sorting destroys original indices. If the answer needs them (LC 1 Two Sum), use a
HashMapinstead. - trap
3Sum: skip a duplicate
iby comparing with the previous value, never the next one. - pro tip
Prove one move out loud: "even with the biggest value left, this one is too small, so it can never be in the answer."
Shaky on a card? Open the chapter or flip its recall cards.