CodeArchon

mediumTwo PointersAmazonBloombergApple

Widest Water Reservoir

A planner inspects a row of posts of varying heights. Picking two posts, the reservoir's water volume equals the shorter post times the distance between them. Maximize it.

Given an integer array `heights`, choose two indices to maximize the area of water trapped: (hi − lo) × min(heights[lo], heights[hi]).

Choose approach

1
0
lo
8
1
6
2
2
3
5
4
4
5
8
6
3
7
7
8
hi
1/18
Narrationstep 1 of 18

Each pair (lo, hi) forms a container of area (hi − lo) × min(h[lo], h[hi]). Start wide and shrink the shorter side.

1def widest_reservoir(heights: list[int]) -> int:
2 lo, hi, best = 0, len(heights) - 1, 0
3 while lo < hi:
4 area = (hi - lo) * min(heights[lo], heights[hi])
5 best = max(best, area)
6 if heights[lo] < heights[hi]:
7 lo += 1
8 else:
9 hi -= 1
10 return best
Variables
lo=0
hi=8
best=0

How to think about it

  1. Area = width × min(two heights). Start with the max width.
  2. If you move the taller side inward, width drops but min can't go up — never better.
  3. Moving the shorter side is the only chance to beat the current area.
  4. Track the running maximum; when pointers meet, you have the answer.

Edge cases to catch in interview

  • Two posts → single area.
  • All equal heights — moving either side is fine.
  • Zero-height posts count as width-only but area is 0.

Examples

Example 149
{"heights":[1,8,6,2,5,4,8,3,7],"values":[1,8,6,2,5,4,8,3,7]}

Posts at indices 1 and 8 give (8−1)×7 = 49.

Example 21
{"heights":[1,1],"values":[1,1]}

Only one container possible.

Try your own input

SpacePlay / pause
← / →Previous / next step
RReset to start
. or >Cycle speed