Trapping Rain Water
Add up the rain water that stays between bars of different heights, using two pointers and no extra arrays.
You are given an array height
Example 1
Input: height = [0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1]Output: 6
Example 2
Output: 9
The Idea
Think of a row of blocks of different heights on a flat floor, like a city skyline seen from the side. Rain that falls on it runs off at the two ends, but it stays in the dips between taller blocks. Example 2 is such a row: bars of height 4, 2, 0, 3, 2 and 5, which we will call bar 0 to bar 5, from the left.
How much water does the whole row hold? Counting dip by dip gets confusing, because a small dip can sit inside a bigger one. A smaller question is easier: how much water stands above one single bar?
Look at the picture below. Bar 2 has height 0. To its left, the tallest bar is bar 0, with height 4. To its right, the tallest is bar 5, with height 5. Water above bar 2 can rise until it spills over the lower of those two, so it reaches level 4, and bar 2 holds 4 - 0 = 4 units.
The same rule works for every bar: take the tallest bar on its left and the tallest bar on its right, keep the lower of the two, and subtract the bar's own height. Bar 1, of height 2, holds 4 - 2 = 2. Bar 3 holds 4 - 3 = 1, and bar 4 holds 4 - 2 = 2. Bar 0 and bar 5 stand at the ends, with nothing beyond them to hold water, so they hold 0. Together that is 2 + 4 + 1 + 2 = 9, the answer of Example 2.
So the water above a bar depends on just three numbers: its own height, the tallest bar on its left and the tallest bar on its right. The real question is how to know those two tallest bars for every bar without searching the row again and again.
Solution Approach
Turning that rule into code means deciding three things: how to find the tallest bar on each side, which side limits the water, and how to add up the water as the bars are visited.
Finding the tallest bar on each side
What is the simplest way to get the two tallest bars? For every bar, scan everything on its left and everything on its right. That is up to n steps per bar for n bars, so about n² steps in total: 100 million for 10,000 bars.
A faster way remembers what it has seen. One pass from the left can record, for each position, the tallest bar up to there, in an array maxLeftmaxRight
Which side limits the water
Do we really need both tallest bars exactly? The rule keeps only the lower of the two. If we already know that one side is the lower one, the exact height of the other side does not matter.
Put one marker, leftrightleftMaxleftrightMaxright
Now suppose the bar at leftleftleftMaxleftleftMax - height[left]right
Settling one bar per step
What happens to the bar a marker leaves behind? Its water is known at that moment, so it is added to the total, and the bar never needs to be looked at again. We say the bar is settled. Walking two markers in from opposite ends like this is called the two-pointer technique.
The steps stop when the markers meet. The bar they meet on is never added, and it does not need to be: no bar in the row is taller than it, so no water stands on it. Every other bar is settled exactly once, and the only extra memory is a few numbers.
Counting water in layers instead
Is there another way to count, if you want one? The rule above counts water column by column. You can also count it in horizontal layers, with a stack: a pile of items where the last item added is the first one taken off. Read the bars from left to right and keep on the stack the positions of bars that could still be the left wall of a dip.
When a taller bar arrives, the bar on top of the stack is the floor of a dip. Take it off: the new top is the left wall, the new bar is the right wall, and the water between them, above the floor, is one flat rectangle. This also takes one pass, but the stack can grow as long as the input, so the code below uses the two markers. The same loop, taking bars off the stack while a taller one arrives, also solves
Java Solution
The method trap
- First, set the two markers:
on the first bar, at 0, andleft on the last bar, atright .height.length - 1 andleftMax start at 0, and so doesrightMax , the running total.water - While
is left ofleft , compare the two bars they point at.right - If
is lower, updateheight[left] with that bar, addleftMax toleftMax - height[left] , and movewater one step right. Becauseleft already includes the bar itself, the amount is never negative, and a new tallest bar adds 0.leftMax - Otherwise, do the same on the right: update
, addrightMax , and moverightMax - height[right] one step left.right - When the markers meet, return
.water
The main[3, 0, 3]
public class TrappingRainWater {
public static int trap(int[] height) {
int left = 0;
int right = height.length - 1;
int leftMax = 0; // tallest bar seen from the left so far
int rightMax = 0; // tallest bar seen from the right so far
int water = 0;
while (left < right) {
if (height[left] < height[right]) {
leftMax = Math.max(leftMax, height[left]);
water += leftMax - height[left]; // right side is sure to be at least as tall
left++;
} else {
rightMax = Math.max(rightMax, height[right]);
water += rightMax - height[right]; // left side is sure to be at least as tall
right--;
}
}
return water;
}
public static void main(String[] args) {
System.out.println(trap(new int[] {0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1}));
System.out.println(trap(new int[] {4, 2, 0, 3, 2, 5}));
System.out.println(trap(new int[] {3, 0, 3}));
System.out.println(trap(new int[] {5, 1, 2}));
System.out.println(trap(new int[] {1, 2, 3}));
System.out.println(trap(new int[] {2, 2, 2}));
System.out.println(trap(new int[] {}));
}
}
Running it prints:
6
9
3
1
0
0
0
The 6 and the 9 at the top match Example 1 and Example 2. The 3 comes from [3, 0, 3][5, 1, 2]
The last three lines are all 0. In the rising slope [1, 2, 3][2, 2, 2]right
The original implementation,
Complexity
The work is one walk of the two markers toward each other, with a fixed amount of work per step.
- Time: O(n), where n is the number of bars. Every step moves either
orleft one place inward, so the loop runs n - 1 times.right - Space: O(1). The method keeps only five
variables, where the version withint andmaxLeft needs two arrays of n numbers.maxRight
Two markers walking in from both ends also find the largest container between two bars in