01
Problem Statement
Given n non-negative integers height[i] representing an elevation map where the width of each bar is 1, compute how much water can be trapped after rain. Water is trapped between bars; each bar has unit width.
- At index
i, the water level above the bar is limited by the minimum of the maximum height to the left and the maximum height to the right. So water ati=max(0, min(maxLeft, maxRight) - height[i]). - We can compute this with two passes (left max and right max arrays) or with two pointers in one pass.
02
Key Observations
- For each index
i, the trapped water above it ismin(maxLeft[i], maxRight[i]) - height[i](if positive), wheremaxLeft[i]is the max height in[0..i]andmaxRight[i]is the max in[i..n-1]. - Two-pointer approach: Maintain
leftandrightandmaxL,maxR(max height seen so far from left and from right). The water at the current position (whichever side we process) is determined by the smaller ofmaxLandmaxR(because that side's "wall" is the bottleneck). So ifheight[left] <= height[right], the water atleftismaxL - height[left](and we updatemaxLandleft++). Else we process from the right similarly.
03
Approach
High-level: left=0, right=n-1, maxL=0, maxR=0, total=0. While left < right: if height[left] <= height[right], water at left is max(0, maxL - height[left]); update maxL, left++. Else: water at right is max(0, maxR - height[right]); update maxR, right--. Add water to total. Return total.
Steps:
left=0,right=n-1,maxL=0,maxR=0,total=0.- While
left < right: ifheight[left] <= height[right]:total += max(0, maxL - height[left]),maxL = max(maxL, height[left]),left++. Else:total += max(0, maxR - height[right]),maxR = max(maxR, height[right]),right--. - Return
total.
04
Implementation
Java
public int trap(int[] height) {
int left = 0, right = height.length - 1, maxL = 0, maxR = 0, total = 0;
while (left < right) {
if (height[left] <= height[right]) {
if (height[left] >= maxL) {
maxL = height[left];
}
else {
total += maxL - height[left];
}
left++;
}
else {
if (height[right] >= maxR) {
maxR = height[right];
}
else {
total += maxR - height[right];
}
right--;
}
}
return total;
}05
Test Cases
Example 1
Input
height = [0,1,0,2,1,0,1,3,2,1,2,1]
Expected
6Explanation
6 units of rain trapped.
06
Complexity Analysis
- Time: O(n).
- Space: O(1).
07
Follow-ups
- Trapping Rain Water II: 2D elevation map.