Trapping Rain Water
Trapping Rain Water is LeetCode 42 (Hard). height[i] is the height of a bar of width 1, and the bars stand side by side.
- After rain, water settles in the dips between bars. Return how many units of water stay trapped.
- Water spills off both ends, so the first and last bars never hold any.
With up to 20,000 bars, checking both sides of every bar is too slow; this page gets it to one pass and constant extra space.
- n == height.length
- 1 <= n <= 2 * 10⁴
- 0 <= height[i] <= 10⁵
Intuition
Look at one bar at a time. The water above it rises to the lower of two walls: the tallest bar on its left and the tallest bar on its right. So the water on bar i is min(leftMax, rightMax) - height[i].
You do not need both maximums exactly. Put a pointer at each end. If the left bar is shorter than the right bar, then somewhere on the right there is already a wall at least as tall as the right bar, so the left side is the lower wall and the left bar's water is leftMax - height[l]. Settle it and step inward. Otherwise settle the right bar the same way.
"Water held between bars" is a two-wall problem: each position is limited by the best wall on each side. That shape also shows up in Container With Most Water and in histogram problems, where the limit is again the smaller side.
Approach
Before reading on, write the water above one bar in terms of the tallest bar on each side. Then ask: if the left end is shorter than the right end, do you need to know anything more about the right side to settle the left bar? Aim for O(n) time and O(1) space.
Two ways to solve it
Walk inward from both ends and settle whichever end is shorter.
- One pass: every bar is settled once.
- No arrays: four integers in total.
The usual interview answer.
Store the tallest bar up to each index from the left and from the right, then add min(left[i], right[i]) - height[i] for every bar.
- Direct: the formula is applied as written.
- Cost: two extra arrays of size n.
The natural first step before two pointers.
Both run in O(n). Two pointers wins because it needs no extra arrays. The steps, code and live demo follow two pointers; the prefix and suffix version comes after the demo.
Start with a pointer at each end
Set l = 0 and r = n - 1, with left_max = right_max = 0 and water = 0. left_max is the tallest bar seen from the left so far and right_max the tallest seen from the right.
Settle the shorter side
If height[l] < height[r], raise left_max to height[l] if it is taller, add left_max - height[l] to water, and move l right. Otherwise do the same on the right with right_max and move r left.
Why the shorter side is safe to settle
Every bar that raised left_max was smaller than some bar at or right of r when it was settled, so the real wall on the right is at least left_max. The water on bar l is therefore exactly left_max - height[l], and nothing found later can change it.
Stop when the pointers meet
Loop while l < r, then return water. The bar where they meet is the tallest seen from both sides, and a tallest bar never holds water, so skipping it loses nothing.
Code in Python, C++ and Java
Prefix and suffix maximums
left[i] is the tallest bar from index 0 up to i, and right[i] the tallest from i to the end. Both include bar i itself, so min(left[i], right[i]) - height[i] is never negative.
Common pitfalls
Adding water before raising the maximum
water += left_max - height[l] left_max = max(left_max, height[l])
left_max = max(left_max, height[l]) water += left_max - height[l]
When the current bar is a new tallest, the old maximum is below it and the difference goes negative. On [2, 0, 2] the first bar settled adds 0 - 2, and the answer comes out 0 instead of 2.
Using the tallest bar in the whole array
top = max(height) water = sum(top - h for h in height)
water += min(left[i], right[i]) - height[i]
Water is held by the lower of the two walls, not the highest bar anywhere. On [3, 0, 1] the wrong version counts 3 + 2 = 5, but the right wall of the middle bar is only 1, so the answer is 1.
Edge cases
For [1, 2, 3, 2, 1], every settled bar is the new tallest on its side, so each adds 0 and the answer is 0.
Water needs a wall on both sides, so the answer is 0. With one bar l == r from the start; with two, each step adds 0.
Complexity
Trapping Rain Water FAQ
Can a monotonic stack solve it too?
Yes. Keep indices of bars in decreasing height. When a taller bar arrives, pop the shorter bar; the new stack top and the arriving bar are its two walls, so add one horizontal layer of water of width i - top - 1. It is O(n) time but O(n) space, and it fills water in layers instead of columns.
What if the bars form a 2D grid?
That is Trapping Rain Water II (LeetCode 407). The single left and right walls become a whole boundary, so you grow inward from the outer edge with a min-heap, always settling the lowest boundary cell first. The idea of settling the lower wall carries over.