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
0lo
8
16
22
35
44
58
63
77
8hi
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.
Variables
lo=0
hi=8
best=0
How to think about it
- Area = width × min(two heights). Start with the max width.
- If you move the taller side inward, width drops but min can't go up — never better.
- Moving the shorter side is the only chance to beat the current area.
- 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 1
49{"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 2
1{"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