Find two lines that form the container holding the most water. Area = width × min(h[left], h[right]). Move the shorter pointer.
TimeO(n)single pass
SpaceO(1)two pointers
Left: —Right: —Max: —
Left
Right
Water
Left
—
Right
—
Max
0
Ready
Press Play. Two pointers at both ends. Area = width × min(h[left], h[right]). Move the shorter pointer inward.
TimeO(n)single pass
SpaceO(n)call stack
Recursive: helper(left, right) — base when left ≥ right return 0; area = width × min; move shorter pointer; return max(area, helper(newLeft, newRight)).
✎ Whiteboard
3
⌨ Type It
Practice until you don't need to look. Use the guide comments below as scaffolding. The green highlights are the nuances to burn into memory.
═══ CONTAINER MOST WATER — TWO POINTERS ═══
PATTERN ▸ Two pointers (move shorter) O(n) · O(1)
① INIT
left, right = 0, len(height)-1
max_water = 0
② LOOP WHILE left < right
while left < right:
③ COMPUTE AREA
w = right - left
h = min(height[left], height[right])
max_water = max(max_water, w * h)
④ MOVE SHORTER POINTER
if height[left] < height[right]: left += 1 else: right -= 1