Trapping Rain Water
Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it can trap after raining.
Examples
height = [0,1,0,2,1,0,1,3,2,1,2,1]
6
6 units of rain water are trapped.
height = [4,2,0,3,2,5]
9
9 units of rain water are trapped.
Constraints
- •
n == height.length - •
1 <= n <= 2 * 10^4 - •
0 <= height[i] <= 10^5
Approaches
For each position, find the max height to the left and right, then compute water.
def trap(height):
total = 0
for i in range(len(height)):
left_max = max(height[:i+1])
right_max = max(height[i:])
total += min(left_max, right_max) - height[i]
return totalPrecompute left_max and right_max arrays, then sum min(left_max[i], right_max[i]) - height[i].
def trap(height):
if not height:
return 0
n = len(height)
left_max = [0] * n
right_max = [0] * n
left_max[0] = height[0]
for i in range(1, n):
left_max[i] = max(left_max[i-1], height[i])
right_max[n-1] = height[n-1]
for i in range(n-2, -1, -1):
right_max[i] = max(right_max[i+1], height[i])
total = 0
for i in range(n):
total += min(left_max[i], right_max[i]) - height[i]
return totalUse two pointers from both ends, tracking left_max and right_max.
Diagram
def trap(height):
left, right = 0, len(height) - 1
left_max, right_max = 0, 0
total = 0
while left < right:
if height[left] < height[right]:
if height[left] >= left_max:
left_max = height[left]
else:
total += left_max - height[left]
left += 1
else:
if height[right] >= right_max:
right_max = height[right]
else:
total += right_max - height[right]
right -= 1
return totalComplexity Comparison
| Approach | Time | Space | Description |
|---|---|---|---|
| Brute Force | O(n^2) | O(1) | For each position, find the max height to the left and right, then compute water. |
| Dynamic Programming | O(n) | O(n) | Precompute left_max and right_max arrays, then sum min(left_max[i], right_max[i]) - height[i]. |
| Two Pointers | O(n) | O(1) | Use two pointers from both ends, tracking left_max and right_max. |
For each position, find the max height to the left and right, then compute water.
Precompute left_max and right_max arrays, then sum min(left_max[i], right_max[i]) - height[i].
Use two pointers from both ends, tracking left_max and right_max.
Common Mistakes
Not considering the minimum of left and right max heights
Using a stack-based approach without understanding when to pop
Forgetting that height at the current position is not included in the water