DSA Visualizer · 25 visualizationsContainer With Most Water
Container With Most Water
You are given an integer array height of length n. Find two lines that, together with the x-axis, form a container that holds the most water. Return the maximum amount of water a container can store.
Start with the widest container: l at the first line and r at the last. The water it holds is the shorter line times the width r − l.
Problem
You are given an integer array height of length n. Find two lines that, together with the x-axis, form a container that holds the most water.
Return the maximum amount of water a container can store.
Examples
Lines at index 1 and 8: min(8,7) × (8 − 1) = 49
Only one pair exists: min(1,1) × 1 = 1
Constraints
- n == height.length
- 2 ≤ n ≤ 10⁵
- 0 ≤ height[i] ≤ 10⁴
Intuition
The widest container uses the two outer lines. Moving the taller line inward can never help — the width shrinks and the height is still capped by the shorter line. So always advance the shorter side, and the area can only get a chance to grow. One pass finds the maximum.
Brute force → Optimal
Try every pair of lines (i, j) and keep the largest min(height[i], height[j]) × (j − i).
Two pointers at the ends. Compute the area, record the best, then move the pointer at the shorter line inward. This is the only move that can expose a taller wall, so a single pass is enough.
Complexity
Edge cases
- Exactly two lines: the loop runs once and the answer is the shorter line times width 1.
- All heights are zero: every area is 0, so the answer is 0.
Common mistakes
- Moving the taller line instead of the shorter one, which can skip over the pair that yields the maximum area.
- Using `r - l + 1` as the width; the distance between two lines at indices l and r is `r - l`.