Skip to content
mlmentorship

Container With Most Water

Pick two heights that hold the most water.

Published · 12 min read ·Core ·Foundation

ML breadth · active recall

Practice before you read

8 minutes. Explain the mechanism, why it works, when it fails, and one alternative.

ML breadth · closed-book attempt

Container With Most Water

Explain the mechanism, why it works, when it fails, and one alternative.

Problem

Input. A list heights of nonnegative integers; index i places a vertical wall at horizontal coordinate i. Output. Return the largest container area formed by two distinct walls and the horizontal ground. Rules. Walls cannot tilt, so the shorter wall limits the water height. Positions are unit-spaced; area is their separation multiplied by the smaller height. Preserve the input and its order. Fewer than two walls return zero. Example. [1, 8, 6, 2, 5, 4, 8, 3, 7] returns 49. Walls at indices 1 and 8 have width 7 and limiting height 7, giving area 7 * 7.

08:00recommended time

Closing or reloading clears the scratchpad. Only score, weak rubric dimensions, attempt count, and retry date can be stored locally.

30-second answer map

Evaluate both boundary walls, then move only the shorter wall because keeping it cannot produce a taller container at a smaller width.

Problem trace

Moving only the taller wall cannot improve the shorter-wall limit

Worked example: keeping the shorter wall cannot improve its current limitWith shorter wall 2 and width 3, area is 6. Moving only the taller wall makes width 2 and height at most 2, so area is at most 4.Keeping the short wall leaves thesame height ceilingCurrent width three; shorter wall twoWater capped atheight 2Area 6; width 3Move only the taller endpoint inwardWater capped atheight 2Area at most 4; width 2
Read it this way: With shorter wall 2 and width 3, area is 6. Moving only the taller wall makes width 2 and height at most 2, so area is at most 4. Can keeping the short wall and reducing width ever beat the current area six?
Full interview answer 12 min read
Reading depth

Choose two vertical walls that can hold the greatest rectangular area of water between them.

Problem

Input. A list heights of nonnegative integers; index i places a vertical wall at horizontal coordinate i.

Output. Return the largest container area formed by two distinct walls and the horizontal ground.

Rules. Walls cannot tilt, so the shorter wall limits the water height. Positions are unit-spaced; area is their separation multiplied by the smaller height. Preserve the input and its order. Fewer than two walls return zero.

Example. [1, 8, 6, 2, 5, 4, 8, 3, 7] returns 49. Walls at indices 1 and 8 have width 7 and limiting height 7, giving area 7 * 7.

Picture: Evaluate Before Discarding a Wall

Problem trace

Separate full input: evaluate the walls before moving the shorter one

Input and goalPick two heights that hold the most water.
Initialize at both endsIndices 0 and 8 give width 8 and area 8. Left height 1 limits area; move left inward.
coveredRange[0..8]bestmax(0, 8) = 8moveL: 0 -> 1reasonleft height 1 < right height 7
covered range
[0..8]
best
max(0, 8) = 8
move
L: 0 -> 1

Recognize it
Choose two boundary positions to maximize width times the smaller boundary height; moving inward always loses width, so only a taller limiting wall can compensate.
Keep true
Before each iteration, best is the largest area among discarded boundary pairs. Moving the shorter wall cannot discard a better pair because every pair that keeps it has smaller width and height no greater than that same short wall.
Reuse it
When moving either boundary worsens one factor, move the boundary responsible for the current bottleneck; retaining that bottleneck cannot improve the objective as the other factor shrinks.
Indices 0 and 8 give width 8 and area 8. Left height 1 limits area; move left inward. Step through the frames to watch the state change. The last frame shows the answer or the stopping condition.
Check: Why can keeping the shorter wall and moving only the taller wall never improve the area?
Reference drawing

Problem trace

Moving only the taller wall cannot improve the shorter-wall limit

Worked example: keeping the shorter wall cannot improve its current limitWith shorter wall 2 and width 3, area is 6. Moving only the taller wall makes width 2 and height at most 2, so area is at most 4.Keeping the short wall leaves thesame height ceilingCurrent width three; shorter wall twoWater capped atheight 2Area 6; width 3Move only the taller endpoint inwardWater capped atheight 2Area at most 4; width 2
Execution trace
Input and goalPick two heights that hold the most water.
Initialize at both endsIndices 0 and 8 give width 8 and area 8. Left height 1 limits area; move left inward.
coveredRange[0..8]bestmax(0, 8) = 8moveL: 0 -> 1reasonleft height 1 < right height 7
covered range
[0..8]
best
max(0, 8) = 8
move
L: 0 -> 1

Recognize it
Choose two boundary positions to maximize width times the smaller boundary height; moving inward always loses width, so only a taller limiting wall can compensate.
Keep true
Before each iteration, best is the largest area among discarded boundary pairs. Moving the shorter wall cannot discard a better pair because every pair that keeps it has smaller width and height no greater than that same short wall.
Reuse it
When moving either boundary worsens one factor, move the boundary responsible for the current bottleneck; retaining that bottleneck cannot improve the objective as the other factor shrinks.
Indices 0 and 8 give width 8 and area 8. Left height 1 limits area; move left inward. Step through the frames to watch the state change. The last frame shows the answer or the stopping condition.
Check: Why can keeping the shorter wall and moving only the taller wall never improve the area?
Read it this way: With shorter wall 2 and width 3, area is 6. Moving only the taller wall makes width 2 and height at most 2, so area is at most 4. Can keeping the short wall and reducing width ever beat the current area six?

Bars show heights; small numbers show indices. The bar’s L=1 denotes left height 1, while code starts at left=0.

Index pairAreaMove
0, 88Discard left height 1
1, 849Discard right height 7
1, 718Discard right height 3
1, 640Equal heights: reference discards right
1, 5; 1, 4; 1, 3; 1, 216; 15; 4; 6Keep best 49

If , any inner partner satisfies . Nonnegative height makes the width comparison safe. Evaluate this bound before deleting left; the taller-wall case is symmetric. With equal heights, either deletion preserves the maximum value, not every tying pair.

Code

def max_area(heights: list[int]) -> int:
   left, right = 0, len(heights) - 1
   best = 0

   while left < right:
      height = min(heights[left], heights[right])
      best = max(best, height * (right - left))
      if heights[left] < heights[right]:
         left += 1
      else:
         right -= 1

   return best

Cost: time and space.

Change 1: Irregular Coordinates

New task. Walls stand at strictly increasing coordinates, supplied alongside equal-length nonnegative heights.

Picture and change. Replace index distance with coordinate distance. Moving inward still reduces width.

Code.

def max_area_positions(positions, heights):
   left, right = 0, len(heights) - 1
   best = 0
   while left < right:
      width = positions[right] - positions[left]
      best = max(best, width * min(heights[left], heights[right]))
      if heights[left] < heights[right]:
         left += 1
      else:
         right -= 1
   return best

Check. Coordinates [0, 2, 5], heights [3, 1, 3], give 15, not index-based area 6.

Use when. Spacing changes but coordinate order remains fixed.

Change 2: Return One Maximizing Pair

New task. Return an index witness as well as area.

Picture and change. Save each strict improvement. Initialize below zero to record a real zero-area pair.

Code.

def max_area_witness(heights):
   left, right = 0, len(heights) - 1
   best, pair = -1, None
   while left < right:
      area = (right - left) * min(heights[left], heights[right])
      if area > best:
         best, pair = area, [left, right]
      if heights[left] < heights[right]:
         left += 1
      else:
         right -= 1
   return {"area": max(best, 0), "indices": pair}

Check. Main input gives area 49, indices [1, 8]; [0, 0] gives area 0, indices [0, 1]. Empty input has area 0 and no witness.

Use when. One certificate suffices; do not promise all ties.

Failure: Moving the Taller Wall

On [1, 2, 4, 3], that rule finds 3 but misses area 4 from indices 1 and 3.

Transfer Check

Does the proof survive rewarding the taller wall instead?

Reasoned Answer

No: the discarded-pair bound used the shorter wall. A changed objective needs a new bound.

What the Invariant Guarantees

best covers evaluated pairs and bounds every discarded pair. All potentially better pairs remain between the boundaries. Each move removes one wall; when pointers meet, no unexamined pair can improve best. This proves the maximum value, not complete enumeration of maximizing indices.

All three implementations use arithmetic operations and constant auxiliary state under ordinary unit-cost arithmetic. The coordinate variant relies on its stated order/length preconditions; it does not validate arbitrary input. The witness uses constant extra storage and does not change input heights.

Sorting [1, 100, 1, 100] changes the answer from 200 to 100 by moving walls. Compare 3Sum: its deletion proof uses sorted values, while this proof uses fixed geometry.