Trapping Rain Water
ArraysTwo PointersDynamic Programming
HardLeetCode #42
Problem Statement
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.
Example
0
1
2
3
4
5
6
7
8
9
10
11
Heights:
0
1
0
2
1
0
1
3
2
1
2
1
Water:
0
0
1
0
1
2
1
0
0
1
0
0
Total Water Trapped: 6 units
Water is trapped between the elevation bars
Trapped Water
Ground/Bars
Input: height = [0,1,0,2,1,0,1,3,2,1,2,1]
Output: 6
Explanation:
- The elevation map is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]
- In this case, 6 units of rain water are trapped
- Water is trapped between the bars based on the height differences
Constraints
- ⢠n == height.length
- ⢠1 ⤠n ⤠2 Ć 10ā“
- ⢠0 ⤠height[i] ⤠3 Ć 10ā“
Solution Approaches
- ⢠Brute Force: For each element, find max height on left and right (O(n²))
- ⢠Dynamic Programming: Precompute max heights for each position (O(n))
- ⢠Two Pointers: Use two pointers to track max heights (O(n), O(1) space)
- ⢠Stack: Use monotonic stack to track trapped water (O(n))
Algorithm Explanation
The Trapping Rain Water problem can be solved efficiently using the two-pointer approach. The key insight is that water level at any position depends on the minimum of the maximum heights to its left and right.
Key Steps (Two Pointers)
- Initialize: Set left and right pointers at array ends, track max heights on both sides.
- Move Pointers: Move the pointer with smaller max height inward.
- Calculate Water: Water trapped = min(left_max, right_max) - current_height.
- Update Max: Update the maximum height for the side we're processing.
Solution Properties
- Time Complexity: O(n) - single pass through array
- Space Complexity: O(1) - only using constant extra space
- Optimal: Uses two pointers to avoid extra space for precomputation
- Intuitive: Water level depends on the bottleneck (minimum of left/right max)
Trapping Rain Water Visualization
Two Pointers Approach
L
0
1
2
3
4
5
6
7
8
9
10
R
11
Left Pointer
Index: 0 | Max: 0
Right Pointer
Index: 11 | Max: 0
Start: Initialize two pointers
Start with pointers at both ends of the array
Total Water Trapped: 0 units
Step 1 of 24
Trapped Water
Ground/Bars
Left Pointer
Right Pointer
Code Example