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 of non-negative integers. Each number is the height of a bar of width 1, and the bars stand side by side in a row. When it rains, water collects in the dips between taller bars. Return how many units of water the row holds, where one unit is a square of width 1 and height 1.

Example 1
Elevation map for heights 0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1 with 6 units of trapped water Input: height = [0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1]
Output: 6
Example 2
Input: height = [4, 2, 0, 3, 2, 5]
Output: 9
Solution

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.

Bars of heights 4, 2, 0, 3, 2, 5 with water between them up to level 4. Bar 2 has height 0, the tallest bar on its left is 4 and on its right is 5, so the water above bar 2 is 4 - 0 = 4.

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 maxLeft. A pass from the right fills maxRight the same way, and a third pass applies the rule. That takes three passes, but also two extra arrays as long as the input.

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, left, on the first bar and another, right, on the last bar. Keep leftMax, the tallest bar from the start up to left, and rightMax, the tallest bar from right to the end. At each step, look at the two bars the markers point at, and move the marker on the lower bar one step inward. The other marker waits.

Now suppose the bar at left is the lower one. Every bar the left marker has moved past was lower than the bar at the right marker at that moment, and all those right-marker bars stand to the right of the current left. So somewhere on the right there is a bar at least as tall as leftMax. The left side is the lower one, and the water at left is leftMax - height[left]. When the bar at right is the lower one, the same reasoning works the other way round.

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 Largest Rectangle in Histogram.

Java Solution

The method trap works in these steps:

  1. First, set the two markers: left on the first bar, at 0, and right on the last bar, at height.length - 1. leftMax and rightMax start at 0, and so does water, the running total.
  2. While left is left of right, compare the two bars they point at.
  3. If height[left] is lower, update leftMax with that bar, add leftMax - height[left] to water, and move left one step right. Because leftMax already includes the bar itself, the amount is never negative, and a new tallest bar adds 0.
  4. Otherwise, do the same on the right: update rightMax, add rightMax - height[right], and move right one step left.
  5. When the markers meet, return water.

The main method runs both examples, a single dip [3, 0, 3], a row whose right side is the lower one, a rising slope, a flat row and an empty array.

Java
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:

Output
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]: the middle bar sits under water up to height 3. Look at the fourth line, 1, from [5, 1, 2]. The bar of height 1 has a 5 on its left but only a 2 on its right, so its water rises to 2, not 5, and there is 2 - 1 = 1 unit.

The last three lines are all 0. In the rising slope [1, 2, 3] and the flat row [2, 2, 2], no bar has a taller bar on both sides. For the empty array, right starts at -1, so the loop never runs.

The original implementation, TrappingRainWater.java, is on GitHub.

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 left or right one place inward, so the loop runs n - 1 times.
  • Space: O(1). The method keeps only five int variables, where the version with maxLeft and maxRight needs two arrays of n numbers.

Two markers walking in from both ends also find the largest container between two bars in Container With Most Water.