Container With Most Water
WHAT IT SAYS
Pick two walls that hold the most water.
WHAT IT'S REALLY ASKING
"Which pairs can we prove are not worth checking?"
Brute force: every pair of walls
O(n²) time · O(1) spaceCheck all n(n−1)/2 pairs, compute min(height) × width, keep the max.
WHERE THE WORK IS WASTED — Most pairs are doomed before you compute them: any pair reusing a short wall at a narrower width was never going to beat what you already have.
The shorter wall condemns all its remaining pairs.
Area = min(hL, hR) × width. Start at maximum width. Narrowing costs width for certain — it only pays off if the height cap rises. But the cap IS the shorter wall, so every remaining pair that keeps the shorter wall is strictly ≤ the container you just measured. Discarding them all at once isn't a guess. It's a proof.
Two pointers, always move the shorter
O(n) time · O(1) spaceStart at both ends. Measure, then move whichever pointer sits on the shorter wall. Each step safely eliminates a whole family of pairs, so n−1 measurements cover all of them.
Pointer as Proof of Elimination
YOU'LL SEE IT AGAIN WHEN
- The answer is a function of a pair (i, j)
- Moving one end gives a monotone argument that whole families of pairs can't win
- One dimension shrinks, so something else must justify the move