Trapping Rain Water
The problem
Section titled “The problem”You get a list of non-negative bar heights, each of width 1. After it rains, water sits in the gaps between taller bars. Return the total units of water trapped.
height = [4, 2, 0, 3, 2, 5] -> 9Between the 4 and the 5, the water levels are 4-2, 4-0, 4-3, 4-2 = 2+4+1+2 = 9.
Key insight
Section titled “Key insight”Look at one position. The water above it is
min(tallest bar to its left, tallest bar to its right) - its own height, never below 0.
The simple fix is two prefix arrays: left_max[i] and right_max[i]. That is O(n) time
and O(n) space. A monotonic stack also works in O(n): it fills water layer by layer as
a taller bar arrives.
To get O(1) space, notice you only need the smaller of the two maxes. Keep two
pointers and a running max for each side. Move the pointer whose bar is shorter. That
side’s bound is its own running max, because the other side already has a bar at least as
tall (the bar under the other pointer), so the lower of the two walls is known. Add
running_max - height and step inward.
Show solutionHide solution
def trap(height: list[int]) -> int: left, right = 0, len(height) - 1 left_max = right_max = 0 water = 0 while left < right: # The side with the smaller wall is bounded by its own running max. if height[left] < height[right]: left_max = max(left_max, height[left]) water += left_max - height[left] left += 1 else: right_max = max(right_max, height[right]) water += right_max - height[right] right -= 1 return waterexport function trap(height: number[]): number { let left = 0; let right = height.length - 1; let leftMax = 0; let rightMax = 0; let water = 0; while (left < right) { // The side with the smaller wall is bounded by its own running max. if (height[left] < height[right]) { leftMax = Math.max(leftMax, height[left]); water += leftMax - height[left]; left++; } else { rightMax = Math.max(rightMax, height[right]); water += rightMax - height[right]; right--; } } return water;}class Solution { public int trap(int[] height) { int left = 0, right = height.length - 1; int leftMax = 0, rightMax = 0; int water = 0; while (left < right) { // The side with the smaller wall is bounded by its own running max. if (height[left] < height[right]) { leftMax = Math.max(leftMax, height[left]); water += leftMax - height[left]; left++; } else { rightMax = Math.max(rightMax, height[right]); water += rightMax - height[right]; right--; } } return water; }}Complexity
Section titled “Complexity”- Time: O(n) — each step moves a pointer inward, so n - 1 steps at most.
- Space: O(1) — two pointers, two running maxes, one total.
Watch out for
Section titled “Watch out for”- Update the max before computing water. If the current bar is a new max, the
water above it is 0, and
max - heightgives exactly that. - Move the shorter side. If you move the taller side, its own running max may be higher than the real limit, which is the lower wall on the other side.
- Empty and tiny inputs.
[], one bar, or strictly rising or falling bars trap nothing. The loop returns 0 for all of them.
Variations
Section titled “Variations”Trapping Rain Water II (LeetCode 407)
Section titled “Trapping Rain Water II (LeetCode 407)”The same idea on a 2D height map. The trick: start from the border cells in a min-heap. Always pop the lowest wall, and push its neighbors, trapping water against the current lowest wall. It is the 2D version of “move the lower side”.
Container With Most Water (LeetCode 11)
Section titled “Container With Most Water (LeetCode 11)”Choose two lines for the biggest container. The trick: the same opposite-ends pointers, always moving the shorter wall. It shares the move rule with this problem.
Largest Rectangle in Histogram (LeetCode 84)
Section titled “Largest Rectangle in Histogram (LeetCode 84)”Another bars problem, solved with the monotonic-stack alternative mentioned above. The trick: keep a stack of increasing heights; when a shorter bar arrives, pop and compute the rectangle each popped bar could span. O(n).