Container With Most Water
On this page
Problem statement
You get n vertical walls of heights
height[0..n−1], standing at x = 0, 1, …, n − 1. Choose two walls; together with the ground they hold water up to the height of the shorter wall. Return the largest amount of water any pair can hold:(j − i) · min(height[i], height[j]). The walls in between don't block the water.
The standard example of the "opposite ends" two-pointer technique, and of a greedy step you have to justify out loud. Original problem: LeetCode 11.
Example

Input: height = [3, 7, 2, 5, 4, 8, 3, 6]
Output: 36 # walls 1 and 7: (7 - 1) * min(7, 6)
Input: height = [4, 3, 2, 1, 4] -> 16 # the two outer walls
Input: height = [1, 1] -> 1
Constraints (assumed)
- 2 ≤ n ≤ 10⁵; 0 ≤ height[i] ≤ 10⁴.
What this question tests
- Spotting that the O(n²) pair search can be cut to O(n) with two pointers from the ends.
- Proving that moving the shorter wall never skips the best answer.
- Not confusing it with Trapping Rain Water, where walls in between do matter.
Questions to ask first
- Do the walls between the two chosen ones matter? (Here: no, they don't block or hold water.)
- Do walls have width? (Here: no, the width is just the index difference.)
- Return the area or the pair of indices? (Here: the area.)
- Can heights be 0? (Yes; such a wall holds nothing.)
Try it yourself first
You have the full problem. Sketch your answer, then sign up free to read the complete walkthrough.
- The complete design, flow by flow, with pictures
- Deep dives into the hard parts
- What mid, senior and staff candidates are expected to say
- Full company question lists
Free forever. No card needed.