FAANGPrep Sprint
Trapping Rain Water
Compute how much water can be trapped after raining.
Examples
The elevation map [0,1,0,2,1,0,1,3,2,1,2,1] traps 6 units of rain water.
Problem Understanding
The Goal
You get an elevation map as an array of n non-negative bar heights, one bar per index and each bar one unit wide. Work out the total amount of rain water that stays trapped between the bars.
Imagine looking at the side profile of a structure built with blocks. When it rains, water fills the "valleys" formed between taller "peaks".
Key Insight
For any given bar at index i, the amount of water it can hold above it is determined by:min(max_height_to_left, max_height_to_right) - height[i]
If this value is negative, it means the bar is taller than the water level, so it holds 0 water.
Algorithm Strategy
The Two Pointer Approach
Instead of pre-computing the max height to the left and right for every index (which takes O(n) space), we can use two pointers to solve this in O(n) time and O(1) space.
- Initialize
left = 0andright = n - 1. - Track
leftMaxandrightMaxseen so far. - The Logic: The amount of water trapped at a position is limited by the shorter of the two boundaries.
- If
leftMax < rightMax: We know the water level at theleftpointer is determined byleftMax(because there's a taller wall somewhere on the right). We moveleftforward, updateleftMax, then addleftMax - height[left]. Updating first means a new tallest bar adds 0 rather than a negative amount. - If
leftMax >= rightMax: We know the water level at therightpointer is determined byrightMax(because there's a taller wall somewhere on the left). We moverightbackward, updaterightMax, then addrightMax - height[right].
- If
Interactive Visualization
6 BARS
MAXES AT THE ENDS
L
R
4
2
0
3
2
5
left_max
4
right_max
5
Water
0
left_max starts at the first bar (4), right_max at the last (5); water 0
Next
left_max 4 < right_max 5: a taller wall exists on the right, so the left side decides. left moves to 1
Heights
Observe how the pointers move inward. The pointer on the side with the smaller max height moves, accumulating water as it goes.
