Problem Statement

Container With Most Water

You are given a list of numbers called height. Each number is the height of a vertical line standing on a flat floor. Line number i stands at position i on the floor and goes up to height[i]. If you pick any two of these lines, they act like the two walls of a container, and the floor between them holds water. The water level can only be as high as the shorter of the two walls, because water would spill over the lower one. Your job is to pick the two lines that hold the most water, and return that largest amount.

mediumArrayTwo PointersTwo PointersTime: O(n) · Space: O(1)

Signals to notice

maximize area between two linesheights as barswidth vs height tradeoff

Brute force first

Check every pair of lines. That instinct is useful because it follows the prompt literally, but it usually keeps revisiting work the problem is begging you to organize.

The key insight

Two pointers at edges, move the shorter line inward. Once you hold onto the right piece of information from moment to moment, the problem feels less like trial and error and more like following a shape that was there all along.

Trace it on height=[1,8,6,2,5,4,8,3,7]

init: left=0, right=8, maxArea=0
L=0(h1) R=8(h7): area=8*min(1,7)=8 -> maxArea=8; h[L]<h[R], left++ -> left=1
L=1(h8) R=8(h7): area=7*min(8,7)=49 -> maxArea=49; h[L]>=h[R], right-- -> right=7
L=1(h8) R=7(h3): area=6*min(8,3)=18 -> maxArea=49; right-- -> right=6
L=1(h8) R=6(h8): area=5*min(8,8)=40 -> maxArea=49; right-- -> right=5
L=1(h8) R=5(h4): area=4*min(8,4)=16 -> maxArea=49; right-- -> right=4
L=1(h8) R=4(h5): area=3*min(8,5)=15 -> maxArea=49; right-- -> right=3
L=1(h8) R=3(h2): area=4; then R=2(h6): area=6 -> both <49; right-- makes right=1, now left>=right, loop ends -> return maxArea=49

What must stay true

Moving the taller line can only decrease area (width shrinks, height can't improve), so always move the shorter one. When you keep that truth intact, each local choice supports the larger solution instead of fighting it.

Shape of the loop

left, right = 0, n-1; maxArea = 0
while left < right:
    area = (right - left) * min(h[left], h[right])
    maxArea = max(maxArea, area)
    if h[left] < h[right]: left += 1   # move the shorter line inward
    else: right -= 1
return maxArea

Pseudocode only — the full worked solution lives in the Solution tab.

Easy way to go wrong

Moving the taller line — you should always move the shorter one to potentially find a taller line. When the code becomes mechanical before the idea is clear, small edge cases start breaking the whole story.

Two Pointers Pattern