Container With Most Water

Free with account Updated Nov 19, 2026 · 4 min read
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

    Walls 1 and 7 are 6 apart and the shorter is 6 high, so they hold 36. The tallest wall, 8, isn't part of the best pair.
    Walls 1 and 7 are 6 apart and the shorter is 6 high, so they hold 36. The tallest wall, 8, isn't part of the best pair.
    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

    1. Do the walls between the two chosen ones matter? (Here: no, they don't block or hold water.)
    2. Do walls have width? (Here: no, the width is just the index difference.)
    3. Return the area or the pair of indices? (Here: the area.)
    4. Can heights be 0? (Yes; such a wall holds nothing.)