Two Pointers
Two indices move through an array or string, and each step discards part of the search space. That turns an O(n²) “try every pair” loop into O(n), often with O(1) extra memory.
When to reach for it
Section titled “When to reach for it”- The input is sorted, or you are allowed to sort it (and the answer is not indices).
- You need a pair or triplet that meets a condition (sum, area, equality).
- You are checking a palindrome or comparing the two ends of a sequence.
- The brute force is a nested loop and the problem asks for O(1) extra space.
- Moving one end has a clear effect: it makes the value bigger or smaller, or it can’t possibly help.
Template
Section titled “Template”left, right = 0, len(items) - 1while left < right: value = measure(items[left], items[right]) if value == goal: record(left, right) left += 1 right -= 1 elif value < goal: # need more: move the pointer that raises it left += 1 else: # need less: move the pointer that lowers it right -= 1The whole skill is the move rule: say why discarding that pointer’s position can never lose the answer. For triplets, sort, fix one number, and run this loop on the rest.
Problems in this guide
Section titled “Problems in this guide”- Valid Palindrome — compare both ends, skipping non-alphanumeric characters
- Container With Most Water — always move the shorter wall inward
- 3Sum — sort, fix one number, two pointers on the rest
- Trapping Rain Water — move the lower side, bounded by its running max