Trapping Rain Water

HardTwo Pointers · Prefix Max🧩 Two PointersLeetCode #42 ↗Updated

Problem

height describes an elevation map of unit-width bars. After it rains, water settles in the dips between bars. Compute the total units of water held above all bars.
Input[0,1,0,2,1,0,1,3,2,1,2,1]Output6
Input[4,2,0,3,2,5]Output9

1 ≤ n ≤ 2·104  ·  0 ≤ height[i] ≤ 105

Try it yourself

Java
class Solution {
    public int trap(int[] height) {
        
    }
}
Your code is saved in this browser.Submit on LeetCode ↗
Key insight
Water above bar i is min(maxLeft(i), maxRight(i)) - height[i]. You only need the smaller of the two maxima — so whichever side has the lower max can be settled immediately.
PatternTwo Pointers

Instinct Sorted input, a pair/triple hitting a target, or something symmetric? Put one pointer at each end and move the one that can only improve things.

Memory hack Squeeze from both ends - every step throws away a whole row of the brute-force grid.

Open the Two Pointers guide →

Approaches

Brute ForceScan Left & Right for Every Bar

Time O(n2)Space O(1)

For each bar, scan to find the tallest bar on its left and on its right (both including itself). The water level there is the lower of the two; subtract the bar's own height. Including the bar makes the result never negative.

Java
public int trap(int[] height) {
    int n = height.length, water = 0;
    for (int i = 0; i < n; i++) {
        int leftMax = 0, rightMax = 0;
        for (int j = 0; j <= i; j++) leftMax = Math.max(leftMax, height[j]);
        for (int j = i; j < n; j++) rightMax = Math.max(rightMax, height[j]);
        water += Math.min(leftMax, rightMax) - height[i];
    }
    return water;
}

Directly encodes the formula, but rescans the array for every bar.

At a glance

LevelApproachTimeSpace
Brute ForceScan Left & Right for Every BarO(n2)O(1)
BetterPrefix / Suffix Max ArraysO(n)O(n)
OptimalTwo Pointers with Running MaximaO(n)O(1)
Common pitfalls
  • Using max of the two sides instead of min for the level.
  • Comparing leftMax/rightMax wrongly — must move the lower side.
  • Adding negative water: update the max before subtracting the bar height.
Interview tips
  • Write the per-bar formula first; every approach is just a faster way to evaluate it.
  • Justify the two-pointer move: the opposite side is guaranteed to be at least as tall.
  • Contrast with Container With Most Water (inner bars ignored there).
Pattern
Prefix/suffix max → two pointers → per-index answers that depend on the max to each side.
My notes saved in this browser