Trapping Rain Water

hard

Given height, an array where height[i] is the height of a bar of width 1, compute how much rain water can be trapped between the bars after it rains.

Hints

How much water sits above one bar? It's bounded by the shorter of its two side maxima.
Water above bar i = min(leftMax, rightMax) - height[i].
Two pointers with running maxima: always advance the shorter side.

Common doubts

Water can only rise to the lower of the two enclosing walls; a taller wall on one side is irrelevant if the other side is shorter.
If height[l] < height[r], the right wall is at least as tall, so min(leftMax, rightMax) for bar l equals leftMax — which you already know. Moving l processes it exactly.
It computes the same min(leftMax, rightMax) on the fly with two running variables, dropping the O(n) space for the prefix/suffix max arrays.

Interview follow-ups

Keep a decreasing stack of bar indices; when a taller bar arrives, pop and add water for the bounded valley — an O(n) alternative that computes water in horizontal layers.
It uses a min-heap over the boundary cells, always processing the lowest boundary — a priority-queue generalization of the shorter-wall idea.

Fun facts

  • Trapping Rain Water is a rite-of-passage two-pointer problem, prized for how the shorter-wall insight collapses O(n) space to O(1).
  • The same 'shorter side binds, advance it' logic drives Container With Most Water.

Asked at

AmazonGoogleMetaMicrosoft
Frequently Sometimes Occasionally
Example 1
Input: height = [0,1,0,2,1,0,1,3,2,1,2,1]
Output: 6
The dips between the bars trap 6 units of water in total.
Example 2
Input: height = [4,2,0,3,2,5]
Output: 9
Water pools between the tall end bars for a total of 9 units.
Constraints

- 1 <= height.length <= 2 * 10^4 - 0 <= height[i] <= 10^5

Solve this problem →