Two Pointers
Loading
Loading
Two Pointers
The elimination argument that makes the technique correct, not just fast.
By the end of this chapter
Two pointers is fast because each iteration discards a candidate forever. If you cannot say which candidate a step eliminates and why it can never be part of the answer, the technique does not apply — it will just be a loop that happens to have two indices.
Concept
Given what I just observed, which side can I rule out entirely? For a sorted pair sum that is: the sum is too small, so the smallest value — already paired with the largest available partner — can never reach the target. It is eliminated.
| Shape | Start | Typical use |
|---|---|---|
| Opposite direction | Both ends, closing in | Pair sums, symmetry, container problems |
| Same direction | Both at the front, different speeds | Filtering, compacting, windows |
def opposite_ends(nums, target): left, right = 0, len(nums) - 1 while left < right: total = nums[left] + nums[right] if total == target: return [left, right] if total < target: left += 1 # nums[left] can never work: eliminated else: right -= 1 return []Can you recognise the pattern?
A sorted array, and a question about a pair or a span that satisfies a numeric condition.
Quick quiz
Sign in to keep a note here. It is free, and nobody else can see it.
Sign inWhat this chapter was for:
Before moving on: take the quiz above, and try 2 practice problems.