hardTwo PointersAmazonGoogleApple
Rooftop Rain Reservoir
A rooftop skyline collects rain in the dips between taller sections. Compute the total volume of water held after a storm.
Given an array `heights` of non-negative bar heights (width = 1), compute how much water can be trapped above the bars after rain.
Choose approach
0
0lo
1
10
22
31
40
51
63
72
81
92
101
11hi
Maptrapped
empty
1/13
Narrationstep 1 of 13
Two pointers from the ends. Water above a position = min(leftMax, rightMax) − height. The lower side bounds the water, so advance it.
Variables
lo=0
hi=11
leftMax=0
rightMax=0
total=0
How to think about it
- At any index, water trapped = min(leftMax, rightMax) − height.
- Precomputing both maxes is O(n) space. We can trim to O(1) with two pointers.
- If h[lo] < h[hi], we know the real rightMax ≥ h[hi] > h[lo] ≥ leftMax — so leftMax is the binding bound. Advance lo.
- Symmetric for hi.
- Each step adds (max of the current side − height) to the total.
Edge cases to catch in interview
- Monotonic non-decreasing or non-increasing bars → 0 water.
- Flat bars → 0 water.
- Single bar → 0 water.
Examples
Example 1
6{"heights":[0,1,0,2,1,0,1,3,2,1,2,1],"values":[0,1,0,2,1,0,1,3,2,1,2,1]}
Example 2
9{"heights":[4,2,0,3,2,5],"values":[4,2,0,3,2,5]}
Try your own input
SpacePlay / pause
← / →Previous / next step
RReset to start
. or >Cycle speed