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.

  1. 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.

  2. use it when

    Sorted array + pair or triplet sum, palindrome check, reverse in place, or keep/remove in place: think two pointers.

  3. template

    Opposite ends: l = 0, r = n - 1; while (l < r) — too small → l++, too big → r--.

  4. template

    Same direction: read scans everything, write marks the next free slot and moves only for keepers.

  5. template

    Two sorted inputs: one pointer each, take the smaller. Merging in place? Fill from the back so nothing is overwritten.

  6. cost

    O(n) time, O(1) extra space. Sorting first adds O(n log n), still far better than O(n²).

  7. trap

    l <= r pairs an element with itself. Pair problems use l < r.

  8. trap

    Sorting destroys original indices. If the answer needs them (LC 1 Two Sum), use a HashMap instead.

  9. trap

    3Sum: skip a duplicate i by comparing with the previous value, never the next one.

  10. 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.