DSA two pointers learning path Level 3 This level · 1 of 1
Hard dsa two-pointers

Trapping Rain Water

The 30 second answer

Water at an index is limited by the shorter of the tallest bars to its left and to its right. I walk from both ends and keep a running left max and right max. The side with the smaller max is already bounded by the other side, so I can add the trapped water there and move that pointer. That is linear time and constant extra space.

Could you say this in an interview?

Problem Given an elevation map as a non-negative integer array, compute how much water it can trap after raining. Water sits above an index only when there are higher bars on both sides. Original: LeetCode 42: Trapping Rain Water.

Understanding the prompt Unlike Container With Most Water, every index can hold water. The water depth at i is min(leftMax[i], rightMax[i]) - height[i], or zero if that value is negative. You need the total over all i.

Pattern recognition Opposite-ends two pointers, using running maxima as the bounds. The same problem also has a monotonic-stack solution.

Brute force For every index, scan left and right for the max bar: O(n²). Precomputing both max arrays is O(n) time and O(n) space.

Optimal Two pointers plus a leftMax and a rightMax. If height[lo] is less than height[hi], the left side is the tighter bound: update leftMax and add leftMax - height[lo], then move lo. Do the symmetric step on the right when the right bar is smaller or equal.

Alternatives Monotonic decreasing stack of indices: when a taller bar arrives, pop and add the water trapped between the new bar and the new top. That is also O(n) time, with O(n) space. Prefix and suffix max arrays are the version that is easiest to prove, at the cost of two extra arrays.

Java solution

public class TrappingRainWater {
    static int trap(int[] height) {
        int lo = 0, hi = height.length - 1;
        int leftMax = 0, rightMax = 0, water = 0;
        while (lo < hi) {
            if (height[lo] < height[hi]) {
                leftMax = Math.max(leftMax, height[lo]);
                water += leftMax - height[lo];
                lo++;
            } else {
                rightMax = Math.max(rightMax, height[hi]);
                water += rightMax - height[hi];
                hi--;
            }
        }
        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})); // 6
        System.out.println(trap(new int[] {4, 2, 0, 3, 2, 5}));                     // 9
        System.out.println(trap(new int[] {1, 1, 1}));                              // 0
    }
}

Complexity O(n) time, O(1) extra space.

Edge cases

  • A strictly increasing or decreasing array traps nothing.
  • Zeros in the middle, as in [4,2,0,3,2,5], which traps 9.
  • A single bar or two bars always return 0.

Follow-ups

  • The 2D version, Trapping Rain Water II, needs a min-heap on the border, not two pointers.
  • Largest Rectangle in Histogram uses a related monotonic stack.

Tests [0,1,0,2,1,0,1,3,2,1,2,1] returns 6. [4,2,0,3,2,5] returns 9. [1,1,1] returns 0.

How to say it in the interview "Water at each index is min of the tallest bar on the left and on the right, minus its own height. I walk from both ends and keep those running maxima. The side with the smaller max is already bounded by the other side, so I can add water there and move in. Linear time, constant space."

Sources (1)
  1. LeetCode 42: Trapping Rain Waterleetcode.com
Previous
Next