Fanpilot

PatternsCore patterns

Two pointers

Chapter 7 of 322 min read

Two pointers work when you can show that moving one pointer never skips an answer. Having two pointers in your code doesn't prove anything by itself; the reason for each move does.

In a sorted list, suppose a[left] + a[right] is less than the target. Every other partner for a[left] is at most a[right], so every sum with a[left] is too small. So left can move forward. If the sum is too large, every other partner for a[right] is at least a[left], so right can move back. Each move rules out a whole row of pairs at once. The pointers move at most n times in total, so it's O(n).

Sorting an unsorted list first costs O(n log n), and you may need to remember the original indexes. If the question is about neighbors in the original order, sorting changes the problem, so you can't always do it.

To remove duplicates from a sorted list, use a read pointer and a write pointer. Everything before write holds the distinct values seen so far, in order. A new value extends that part; a duplicate is skipped. What's left after write doesn't matter.

3Sum fixes one value, then runs the sorted two-pointer search on the rest. After sorting, that's O(n²). Skipping repeated fixed values and repeated pointer values avoids duplicate triples. The goal is unique triples of values; a different output rule would need different duplicate handling.

A different reason: in Container With Most Water, the shorter wall limits the height. Moving the taller wall inward makes the container narrower without raising that limit, so it can't help. Move the shorter wall instead. This reason is different from the sorted-sum one.

Fast and slow pointers rely on yet another fact. In a cycle of length c, the fast pointer gains one step on the slow one each move, so they meet. Finding where the cycle starts needs one more argument about distances. Don't treat every two-pointer problem as one template.

Practice: LC 167 Two Sum II, LC 26 Remove Duplicates from Sorted Array, LC 15 3Sum, LC 11 Container With Most Water, LC 141 Linked List Cycle, LC 142 Linked List Cycle II.

Check your understanding: Name every pair that one pointer move rules out. Would that still be safe if the list weren't sorted? Does your reasoning allow equal values, and what happens with duplicates?