Algorithms · Two pointers
Container With Most Water
Pick two walls that hold the most water between them.
The problem
Each number is the height of a wall. Pick two walls: the water between them is the shorter wall × the distance between them. Return the most water any two walls can hold.
most_water([1, 8, 6, 2, 5, 4, 8, 3, 7])→49most_water([1, 1])→1Start with the way that works
This version is correct. It is also the slow one. Read it first: the fast way is easier to find once you can see what the slow way wastes.
def most_water(h):take the wall heights best = 0the most water so far for i in range(len(h)):pick a left wall for j in range(i + 1, len(h)):and a right wall water = min(h[i], h[j]) * (j - i)shorter wall times the gap best = max(best, water)keep the biggest return bestthe most waterNow ask: what if there were a billion?
With a billion walls, just reading them takes a while. That’s the floor: no method can beat O(n) when every wall might matter. Getting there means you’ve hit the best possible.
Aim for O(n)🔥 boss
Think it through
Walls at both ends hold some water. Which wall limits it?
- The taller one
- The shorter one
Show the answer
The shorter one. Water spills over the shorter wall. So the short wall decides the height, whatever the tall one does.
To try for more water, which wall do you move inwards?
- The taller one
- The shorter one
Show the answer
The shorter one. Moving the tall wall can only lose: the gap shrinks and the short wall still limits you. Moving the short wall is the only move that might find a taller one.
Stuck? 3 nudges, smallest first
- Start with the two outermost walls: they’re the furthest apart.
- The water is limited by the shorter wall. Moving the taller wall inwards can never help, because the gap shrinks and the short wall still limits you.
- While
i < j: updatebest, then move the shorter wall inwards (i += 1ifh[i] < h[j], elsej -= 1).
The fast way
Try it yourself before you open this. The slow version above already passes every test, so you can change it one step at a time.
Show the fast version
def most_water(h):take the wall heights i, j, best = 0, len(h) - 1, 0the two outermost walls; no water yet while i < j:until the walls meet best = max(best, min(h[i], h[j]) * (j - i))water between these two if h[i] < h[j]:the left wall is the short one i += 1only a taller left wall could do better else:the right wall is the short one j -= 1so move the right wall in return bestthe most waterSolve it yourself.
It runs right in the page: the tests, the gremlins that try to break it, and a race up to a billion. Free, nothing to install.