Skip to content
Back to notes
Oct 17, 2026
Medium

Container With Most Water

best pair where the value depends on the width (distance) and the smaller of the two → two pointers from both ends, move the limiting side. Start as wide as possible; each step gives up width, so the only hope is a taller limiting bar, so throw away the shorter one. The proof idea to remember: the shorter bar has already had its best container (the widest one), so drop it.
  • array
  • two pointers
  • greedy

Problem

You are given an integer array heights where heights[i] is the height of the ii-th bar. You may choose any two bars to form a container. Return the maximum amount of water a container can store.

Example 1

Input:  height = [1,7,2,5,4,7,3,6]
Output: 36

Bars at indices 1 and 7 (heights 7 and 6): width 7 - 1 = 6, height min(7, 6) = 6, area 6 * 6 = 36.

Example 2

Input:  height = [2,2,2]
Output: 4

Constraints

  • 2 <= len(height) <= 100000
  • 0 <= height[i] <= 10000

Thinking

  • Brute force idea: try every pair i < j, area = (j - i) * min(h[i], h[j]), keep the max. O(n2)O(n^2), ~5 billion pairs at n=100000n = 100000, so too slow.
  • Key insight: start with the widest container (l = 0, r = n - 1) and always move the shorter side inward. Why that’s safe: say h[l] <= h[r]. Every other container that uses l pairs it with some r' < r. It’s narrower, and its height is still at most h[l] (the water level is capped by the shorter bar). So none of them can beat the current area, and bar l can be dropped for good. Moving the taller side instead could never help: the width shrinks and the height stays capped by the same short bar. Each step drops one bar → O(n)O(n) time, O(1)O(1) space.
  • Edge cases to remember: n = 2 (only one container); zero heights (area 0); equal heights (moving either side is fine); the best pair isn’t the two tallest bars ([1,7,2,5,4,7,3,6] → 7 and 6, not 7 and 7, because the width matters).

Solution

Approach A — my version: two pointers, move the shorter side ✅ best practice

Complexity: Time O(n)O(n) · Space O(1)O(1)

Already optimal. Compute the area at each step, then move the pointer at the shorter bar. On a tie it moves l, which is fine: when h[l] == h[r], no container using either bar can beat the current one, so either can be dropped.

def max_area_mine(heights: list[int]) -> int:
    l = 0
    r = len(heights) - 1
    max_area = 0
    while l < r:
        max_area = max(max_area, (r - l) * min(heights[l], heights[r]))
        if heights[l] > heights[r]:
            r -= 1
        else:  # shorter (or equal) bar on the left -> drop it
            l += 1

    return max_area

Approach B — brute force, every pair

Complexity: Time O(n2)O(n^2) · Space O(1)O(1)

Checks every pair. Obviously correct, so the tests use it as a reference on random inputs, but it times out at the real constraint size.

def max_area_brute(heights: list[int]) -> int:
    n = len(heights)
    best = 0
    for i in range(n - 1):
        for j in range(i + 1, n):
            best = max(best, (j - i) * min(heights[i], heights[j]))
    return best

Approach C — two pointers, skip bars that can’t help

Complexity: Time O(n)O(n) · Space O(1)O(1)

Same algorithm, constant-factor speedup. After computing an area with water level level = min(h[l], h[r]), every bar that is not taller than level can be skipped without computing its area: it’s narrower and no taller, so it can’t beat the area just recorded. The inner while loops are cheap compared with max/min calls.

def max_area_skip(heights: list[int]) -> int:
    l, r = 0, len(heights) - 1
    best = 0
    while l < r:
        level = min(heights[l], heights[r])
        best = max(best, (r - l) * level)
        while l < r and heights[l] <= level:  # narrower and no taller -> can't win
            l += 1
        while l < r and heights[r] <= level:
            r -= 1
    return best

Scratch / Experiments

The two-pointer versions always do about nn steps, so the input is just random heights at the max size (n=100000n = 100000). The brute force is timed at n=2000n = 2000 only (~2 million pairs).

Measured (one run): at n=100000n = 100000, mine ~9.1 ms, with skipping ~2.9 ms. At n=2000n = 2000, brute force ~136 ms vs mine ~0.19 ms (~700×, and the gap grows linearly with nn). The skip version is ~3× faster with the same Big-O: on random heights most inner bars are shorter than the current water level, so they’re passed over with one comparison each, instead of a multiply plus the max()/min() function calls, which are slow in Python.

rng = random.Random(0)
heights = [rng.randint(0, 10000) for _ in range(100000)]
assert max_area_mine(heights) == max_area_skip(heights)
%timeit max_area_mine(heights)
%timeit max_area_skip(heights)

small = heights[:2000]
assert max_area_brute(small) == max_area_mine(small)
%timeit -n 1 -r 3 max_area_brute(small)
%timeit max_area_mine(small)

Takeaways

  • Pattern: best pair where the value depends on the width (distance) and the smaller of the two → two pointers from both ends, move the limiting side. Start as wide as possible; each step gives up width, so the only hope is a taller limiting bar, so throw away the shorter one. The proof idea to remember: the shorter bar has already had its best container (the widest one), so drop it.
  • Mistakes I made: none, it’s the optimal solution. Things to keep in mind:
    • Be ready to explain why moving the shorter side never skips the answer. That’s what an interviewer will ask.
    • A tie can move either pointer.
    • Micro-optimization: after computing an area, skip all bars no taller than the current water level (Approach C).
  • Related problems: Trapping Rain Water (#42, also two pointers from both ends moving the shorter side, but it sums the water above every bar instead of picking one pair), Two Sum II (#167, two pointers from both ends on a sorted array), 3Sum (#15, sort + two pointers), Largest Rectangle in Histogram (#84, area limited by the shortest bar, solved with a monotonic stack), Valid Palindrome (#125, two pointers moving inward).