LeetCode 11 · Medium · Two Pointers

Container With Most Water

Each value in height is a vertical wall at that index. Pick two walls so that, together with the floor, they hold the most water, and return that amount: the distance between them times the shorter wall.

O(n)time
O(1)space
move the shorterwall inward

2–16 integers, 0 to 99

×=

Legend blue box = water between walls l and r · dashed = best container so far · grey walls are ruled out

public int maxArea(int[] height) { int l = 0; int r = height.length - 1; int res = 0; while (l < r) { int area = (r - l) * Math.min(height[l], height[r]); res = Math.max(res, area); if (height[l] < height[r]) { l++; // the shorter wall cannot do better } else { r--; } } return res;}
l
—
r
—
area
—
res
0

Why it works

  1. Brute force tries every pair of walls: n(n − 1)/2 areas, O(n²).
  2. The shorter wall is finished. Start with the widest container. Any other container that keeps the shorter wall is narrower, and its water level is still capped by that wall, so it holds less. Drop the shorter wall and lose nothing.
  3. Why O(n): each step rules out one wall for good, so the pointers meet after n − 1 steps. Two indices and the best area are the only memory.
  4. Pitfall: moving the taller wall is wrong: the width shrinks while the level stays capped by the same short wall. And the water level is the shorter wall, not the average.
  5. Ties: when both walls are equal, moving either one is safe. Neither can pair with anything inside for more water than now.
  6. Related: Trapping Rain Water also walks two pointers inward from the shorter side, but sums water over every column.