CodeArchon

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
0
lo
1
1
0
2
2
3
1
4
0
5
1
6
3
7
2
8
1
9
2
10
1
11
hi
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.

1def trapped_rain(heights: list[int]) -> int:
2 lo, hi = 0, len(heights) - 1
3 left_max = right_max = total = 0
4 while lo < hi:
5 if heights[lo] < heights[hi]:
6 left_max = max(left_max, heights[lo])
7 total += left_max - heights[lo]
8 lo += 1
9 else:
10 right_max = max(right_max, heights[hi])
11 total += right_max - heights[hi]
12 hi -= 1
13 return total
Variables
lo=0
hi=11
leftMax=0
rightMax=0
total=0

How to think about it

  1. At any index, water trapped = min(leftMax, rightMax) − height.
  2. Precomputing both maxes is O(n) space. We can trim to O(1) with two pointers.
  3. If h[lo] < h[hi], we know the real rightMax ≥ h[hi] > h[lo] ≥ leftMax — so leftMax is the binding bound. Advance lo.
  4. Symmetric for hi.
  5. 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 16
{"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 29
{"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