Two pointers: walking an array from both ends
Finding two values that add up to a target looks like a job for every pair, and n values have about n²/2 of them. In a sorted array, two indexes, one at each end, rule out a whole row of pairs with every move.
01 Every pair, or something better
The question: in [1, 2, 4, 5, 6, 8, 10, 15], which two values add up to 13? The plain answer tries every pair: 1 with each value after it, then 2 with each value after it, and so on.
Eight values make 8 × 7 / 2 = 28 pairs. A thousand values make about 500,000. The loop works on any array, sorted or not, and that is exactly its weakness: it ignores the one fact that could save it work.
02 Two indexes, one at each end
Put L on the smallest value and R on the largest. Add them. If the sum is too big, move R left to a smaller value. If it is too small, move L right to a bigger one. Stop when the sum hits the target or the two meet.
The table below the array holds all 28 sums. Watch how much of it each move crosses out.
- between L and R
- the pair to sum next
- ruled out
- the answer
Eight sorted values make 28 pairs, and any of them could add up to 13. L starts at the smallest value and R at the largest.
03 Why one sum rules out a whole row
Look at the first move. 1 + 15 = 16 is too big. Every other value 15 could pair with sits between L and R, and in a sorted array they are all at least 1. So every pair with 15 is at least 16. You never need to try them: one sum told you about seven pairs.
The other direction is the mirror image. When 1 + 10 = 11 is too small, 10 is the biggest partner 1 has left, so every pair with 1 is at most 11. 1 can go.
Each move throws away one value for good, and the pairs it took with it are pairs that could not work. With n values, L and R meet after at most n − 1 moves.
The whole argument rests on one fact: everything between L and R is at least nums[L] and at most nums[R]. Take away sorted order and a too-big sum tells you nothing about the other pairs.
04 The loop in code
The code is shorter than the argument. Each comment says which value just ran out of useful partners.
while left < right, not <=: when the two meet there is one value left, and a value cannot pair with itself. The loop runs at most n − 1 times and uses no extra memory, so it is O(n) time and O(1) space.
05 The same move in other problems
The pattern is always the same: a comparison tells you that one of the two values can never be part of a better answer, so you drop it. What changes is the comparison.
| Problem | Where the pointers start | Which one moves, and why |
|---|---|---|
| Pair with a given sum | Both ends | Too big: `R` moves, its column is too big. Too small: `L` moves. |
| Container with most water | Both ends | The shorter wall. It caps the water level, and every narrower container with that wall holds no more. |
| Is it a palindrome? | Both ends | Both, every step, while the two characters match. |
| 3Sum | Fix one value, then both ends of the rest | As for a pair, once per fixed value: `O(n²)` instead of `O(n³)`. |
| Remove duplicates in place | Both at the start | `fast` reads every value; `slow` moves only when it writes a new one. |
The last row is the other family: both pointers start on the left and move at different speeds. It skips no pairs; it lets you read and write the same array in one pass.
06 When it breaks
nums = [8, 1, 15, 4]The input is not sortedA too-big sum then says nothing about the other pairs. Sorting first costs O(n log n) and loses the original indexes; if the problem wants those, as unsorted Two Sum does, a hash map is the better tool.while left <= right:A value paired with itselfWhen left == right, the sum is one value doubled. For target 10 and a lone 5, the loop reports a pair that does not exist.if height[l] > height[r]:
l += 1Moving the wrong pointerIn Container With Most Water, moving the taller wall never helps: the width shrinks and the shorter wall still caps the level. The proof only holds for the move it was made for.[-1, -1, 0, 1, 2]Duplicates in 3SumFixing the first -1 and then the second finds [-1, 0, 1] twice. Skip a value equal to the one you just used, for the fixed value and for L and R after a hit.