Container With Most Water

MediumTwo Pointers · Greedy Shrink🧩 Two PointersLeetCode #11 ↗Updated

Problem

height[i] is the height of a vertical wall standing at x-position i. Pick two walls; together with the x-axis they form a container whose water level is limited by the shorter wall. Return the largest amount of water any pair can hold, i.e. max of min(h[i], h[j]) × (j - i).
Input[1,8,6,2,5,4,8,3,7]Output49
Input[1,1]Output1

2 ≤ n ≤ 105  ·  0 ≤ height[i] ≤ 104

Try it yourself

Java
class Solution {
    public int maxArea(int[] height) {
        
    }
}
Your code is saved in this browser.Submit on LeetCode ↗
Key insight
Start with the widest pair. The shorter wall is the bottleneck: pairing it with any wall further inside only shrinks the width while its height cap stays the same, so it can never do better — discard it and move inward.
PatternTwo Pointers

Instinct Sorted input, a pair/triple hitting a target, or something symmetric? Put one pointer at each end and move the one that can only improve things.

Memory hack Squeeze from both ends - every step throws away a whole row of the brute-force grid.

Open the Two Pointers guide →

Approaches

Brute ForceTry Every Pair of Walls

Time O(n2)Space O(1)

For every pair i < j, the water is min(height[i], height[j]) * (j - i). Track the maximum over all n(n-1)/2 pairs.

Java
public int maxArea(int[] height) {
    int maxArea = 0;
    for (int i = 0; i < height.length; i++) {
        for (int j = i + 1; j < height.length; j++) {
            int area = Math.min(height[i], height[j]) * (j - i);
            maxArea = Math.max(maxArea, area);
        }
    }
    return maxArea;
}

Direct translation of the definition — times out for n = 105.

At a glance

LevelApproachTimeSpace
Brute ForceTry Every Pair of WallsO(n2)O(1)
OptimalTwo Pointers — Move the Shorter WallO(n)O(1)
Common pitfalls
  • Moving the taller wall — can skip the optimal pair.
  • Confusing with Trapping Rain Water: here only two walls matter, inner walls are ignored.
  • Using max instead of min of the heights for the water level.
Interview tips
  • Give the brute force, then ask “which pairs can I rule out?”
  • Prove the greedy step: width shrinks, height is capped by the short wall.
  • On ties, moving either pointer is fine — mention it.
Pattern
Opposite-end two pointers with greedy discard → optimise a pair score that depends on distance and the min of two values.
My notes saved in this browser