Container With Most Water (LeetCode 11): Solution and Explanation

Medium
Array
Two Pointers
Greedy

You are given the heights of vertical lines placed at evenly spaced positions. Choose two lines that, together with the x-axis, form a container holding the most water, and return that maximum area.

Variables
No variables to display
DepthFunction Call
Stack empty
0/0

Intuition

The area between lines l and r is the distance between them times the shorter of the two heights, because water spills over the lower side. The brute force checks every pair, which is O(n²). To do better you need a rule that lets you rule out many pairs at once without checking them.

Start with the widest possible container, l = 0 and r = n - 1. Now suppose height[l] is the shorter line. Any other container that keeps l and uses some r' between them is narrower, and its height is still capped by height[l], so its area can only be smaller or equal. In other words, the shorter line has already achieved its best possible container. It is safe to discard it and move l inward. The same argument applies to r when it is the shorter one.

That is the whole algorithm. Compute the current area, record it if it is the best so far, then move whichever pointer has the shorter line. Moving the taller line can never help, since the width shrinks and the height is still limited by the shorter side. Each step eliminates one line from consideration, so after n - 1 steps every line has either been paired with its best partner or proven useless.

It helps to say out loud why this greedy choice is not just a heuristic. A heuristic might skip the best pair. Here, every pair you never compute contains a line that was discarded at a moment when it was the shorter side, and the argument above shows such a pair cannot beat the area recorded at that moment, so nothing better is ever skipped.

Approach: Greedy two pointers

  1. Set l = 0, r = len(height) - 1 and res = 0.
  2. While l < r, compute area = (r - l) * min(height[l], height[r]).
  3. Update res = max(res, area).
  4. If height[l] < height[r], increment l, since the left line cannot do better.
  5. Otherwise decrement r. When the heights are equal, either choice is safe.
  6. Return res once the pointers meet.

Step-by-step example

height = [1, 8, 6, 2, 5, 4, 8, 3, 7]
  1. l = 0, r = 8: area = 8 × min(1, 7) = 8. res = 8. The left line (1) is shorter, so l = 1.
  2. l = 1, r = 8: area = 7 × min(8, 7) = 49. res = 49. The right line is shorter, so r = 7.
  3. l = 1, r = 7: area = 6 × 3 = 18. r = 6. Then area = 5 × 8 = 40; heights are equal, so r = 5.
  4. The remaining pairs give 4 × 4 = 16, 3 × 5 = 15, 2 × 2 = 4 and 1 × 6 = 6, none better than 49.
  5. The pointers meet and the function returns 49.

Code: Python, Java, C++

1class Solution:
2    def maxArea(self, height: List[int]) -> int:
3        l, r = 0, len(height) - 1
4        res = 0
5
6        while l < r:
7            area = (r - l) * min(height[l], height[r])
8            res = max(res, area)
9
10            if height[l] < height[r]:
11                l += 1
12            else:
13                r -= 1
14        
15        return res

Time and space complexity

Time

O(n)

Every iteration moves one pointer inward by one, so the loop runs at most n - 1 times with constant work each.

Space

O(1)

Only two pointers and the running maximum are stored.

Other approaches

Brute force over all pairs (time O(n²), space O(1))

Compute the area for every pair i < j and keep the maximum. It is obviously correct and handy for testing, but it is quadratic and too slow for 10^5 lines.

Two pointers with skipping (time O(n), space O(1))

Same greedy, but after moving a pointer, keep moving it while the new line is not taller than the one just discarded, since such lines cannot improve the area. It has the same bound and sometimes saves iterations.

Common mistakes

  • Moving the pointer at the taller line. That throws away the line that might still form a larger container and can miss the optimum.
  • Using the larger height in the area formula. Water level is limited by the shorter line, so the height is min(height[l], height[r]).
  • Confusing this problem with Trapping Rain Water. Here only two lines matter and the lines in between have no effect on the area.
  • Computing the width as r - l + 1. The width is the distance between the lines, which is r - l.

Frequently asked questions

Why do we move the shorter line in Container With Most Water?

The shorter line limits the height of every container it forms. Pairing it with any line closer in can only reduce width without raising the height, so it has already reached its best area and can be discarded.

What is the time complexity of Container With Most Water?

O(n), because each step moves one of the two pointers inward and the loop ends when they meet.

What happens when both heights are equal?

Either pointer can move. Any container that keeps one of these lines is narrower and still capped by the same height, so neither line can do better.

How is this different from Trapping Rain Water?

This problem picks two lines and ignores everything between them. Trapping Rain Water sums the water above every bar, which depends on the tallest bars to the left and right of each position.