Trapping Rain Water
Master this topic with zero to advance depth.
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.
Visual Representation
Elevation Map: [0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1]
Bars: #
# ## #
# ## # ######
010210132121
Water trapped (W):
#
# WW #
#W##W######
Total Trapped: 6 unitsExamples
The elevation map [0,1,0,2,1,0,1,3,2,1,2,1] traps 6 units of rain water.
Level I: Brute Force (Iterate per Unit of Water)
Intuition
For each element, the amount of water it can trap is determined by the maximum height to its left and its right. Water level = min(maxLeft, maxRight) - currentHeight.
Detailed Dry Run
Input: [0, 1, 0, 2]
Index 2 (height 0): maxL=1, maxR=2. min(1, 2) - 0 = 1. Total = 1.
⚠️ Common Pitfalls & Tips
O(N^2) is very slow for large inputs (N=10^5).
Level II: Precomputing Max Left/Right
Intuition
Instead of re-calculating maxLeft and maxRight for every index, we can precompute them using two arrays in O(N).
Create leftMax array where leftMax[i] stores max height from index 0 to i. Create rightMax array similarly for index i to n-1.
Detailed Dry Run
Input: [0, 1, 0, 2]
leftMax: [0, 1, 1, 2]
rightMax: [2, 2, 2, 2]
Water at index 2: min(1, 2) - 0 = 1.
⚠️ Common Pitfalls & Tips
O(N) space is used for the auxiliary arrays.
Level III: Optimal (Two Pointers)
Intuition
At any index i, the water trapped is min(maxLeft, maxRight) - height[i]. Instead of precalculating max arrays, we can use two pointers from ends. The pointer with the smaller max determines the water level for that side.
Detailed Dry Run
Input: [4, 2, 0, 3, 2, 5]
l=0, r=5.LMax=4, RMax=5.4 < 5, movelto 1.l=1:height=2.Water += 4-2=2.l=2.l=2:height=0.Water += 4-0=4.l=3.l=3:height=3.Water += 4-3=1.l=4.l=4:height=2.Water += 4-2=2.l=5. Total water: 2+4+1+2 = 9.
⚠️ Common Pitfalls & Tips
Be careful with the update condition: only add water if the current height is less than the current side's max height.
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.