Trapping Rain Water
Difficulty: Hard · Pattern: Two Pointers · LeetCode #42
height describes an elevation map of bars, each 1 unit wide. After it rains, water collects in the dips between bars. Return the total units of trapped water.
Examples
text
height = [3, 0, 2, 0, 4] → 7 (3 + 1 + 3)
height = [0, 1, 0, 2, 1, 0, 1, 3] → 5Hints
- Water above bar i = min(tallest bar to its left, tallest bar to its right) − height[i], if positive.
- Precomputing left-max and right-max arrays gives O(n) time and O(n) space.
- With two pointers, the side with the smaller running max is already "decided".
Approach
Water at i is min(maxLeft[i], maxRight[i]) − height[i]. Instead of two arrays, keep two pointers and running maxima lm and rm.
If lm < rm, the water at l is bounded by lm: there is a wall of height rm ≥ lm somewhere on the right, so the right side can't be the limit. Add lm − height[l] and move l. Otherwise do the symmetric step on the right. Each bar is processed once.
Complexity
Time: O(n). Space: O(1).
Python solution
def trap(height):
l, r = 0, len(height) - 1
lm = rm = water = 0
while l < r:
lm = max(lm, height[l])
rm = max(rm, height[r])
if lm < rm:
water += lm - height[l]
l += 1
else:
water += rm - height[r]
r -= 1
return waterJavaScript solution
function trap(height) {
let l = 0, r = height.length - 1, lm = 0, rm = 0, water = 0;
while (l < r) {
lm = Math.max(lm, height[l]);
rm = Math.max(rm, height[r]);
if (lm < rm) { water += lm - height[l]; l++; }
else { water += rm - height[r]; r--; }
}
return water;
}