Two Pointers · Area

Container With Most Water Visualizer

What is Container With Most Water

Each height[i] is a vertical line at x = i. Two lines form a container whose width is the distance between them and whose water stops at the shorter line. Return the largest area. Checking every pair is too slow on the large test.

1 8 6 2 5 4 8 3 7
49

Approach

Every pairThere are a quadratic number of pairs. The large test rejects that scan.
Start wide, drop the short sideThe widest container is the one between the ends. A taller area needs a taller limiting line, so move the pointer on the shorter line inward.

Interactive solution

The shaded water between the two pointers
L, R = 0, n - 1
best = 0
while L < R:
area = (R - L) * min(h[L], h[R])
if h[L] <= h[R]: L += 1
else: R -= 1
return best
Step 0/0 Answer —

The finished picture is on screen when the page opens. Next and Play start again from the first step.

Complexity

PieceCostWhy
TimeO(n)Each step moves one pointer, and they meet once.
MemoryO(1)Only the two pointers and the best area are stored.

Implementation

def max_area(h):
    l, r, best = 0, len(h) - 1, 0
    while l < r:
        best = max(best, (r - l) * min(h[l], h[r]))
        if h[l] <= h[r]:
            l += 1
        else:
            r -= 1
    return best