LeetCode #42 Hard

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.

Constraints
  • n == height.length
  • 1 <= n <= 2 * 10⁴
  • 0 <= height[i] <= 10⁵
arraytwo-pointers
Open on LeetCode ↗
02

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.

How to spot this pattern

"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.

03

Approach

Try it first

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.

1

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.

2

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.

3

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.

4

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.

04

Code in Python, C++ and Java

▶1class Solution:
▶2 def trap(self, height):
▶3 l, r = 0, len(height) - 1
▶4 left_max = right_max = 0
▶5 water = 0
▶6 while l < r:
▶7 if height[l] < height[r]:
▶8 left_max = max(left_max, height[l])
▶9 water += left_max - height[l]
▶10 l += 1
▶11 else:
▶12 right_max = max(right_max, height[r])
▶13 water += right_max - height[r]
▶14 r -= 1
▶15 return water
0L10210132121Rleft wall0right wall0water0pointers at both ends, no water yet
l0
r11
water0
L starts on the first bar and R on the last. Both walls start at 0, and each step will settle exactly one bar: decide its water for good and move past it.
01L0210132121Rleft wall0right wall0water0left end lower → bar 0 holds 0
bar0height 0
left wall0
water0
The left end is shorter than the right end, so the right side already has a wall at least that tall. Bar 0 is as tall as the left wall, so it holds nothing.
01L021013212R1left wall0right wall1water0ends equal → bar 11 is a new wall
bar11height 1
right wall1
water0
The left end is not shorter, so the left side already has a wall at least as tall as the right end. Bar 11 is taller than every bar before it on this side, so it holds nothing and becomes the new right wall: 1.
010L21013212R1left wall1right wall1water0left end lower → bar 1 is a new wall
bar1height 1
left wall1
water0
The left end is shorter than the right end, so the right side already has a wall at least that tall. Bar 1 is taller than every bar before it on this side, so it holds nothing and becomes the new left wall: 1.
0102L1013212R1left wall1right wall1water1left end lower → bar 2 holds 1
bar2height 0
left wall1
water1
The left end is shorter than the right end, so the right side already has a wall at least that tall. Bar 2 sits 1 below the left wall of height 1, so 1 unit of water stays on it.
0102L101321R21left wall1right wall2water1ends equal → bar 10 is a new wall
bar10height 2
right wall2
water1
The left end is not shorter, so the left side already has a wall at least as tall as the right end. Bar 10 is taller than every bar before it on this side, so it holds nothing and becomes the new right wall: 2.
0102L10132R121left wall1right wall2water2right end lower → bar 9 holds 1
bar9height 1
right wall2
water2
The left end is not shorter, so the left side already has a wall at least as tall as the right end. Bar 9 sits 1 below the right wall of height 2, so 1 unit of water stays on it.
0102L1013R2121left wall1right wall2water2ends equal → bar 8 holds 0
bar8height 2
right wall2
water2
The left end is not shorter, so the left side already has a wall at least as tall as the right end. Bar 8 is as tall as the right wall, so it holds nothing.
01021L013R2121left wall2right wall2water2left end lower → bar 3 is a new wall
bar3height 2
left wall2
water2
The left end is shorter than the right end, so the right side already has a wall at least that tall. Bar 3 is taller than every bar before it on this side, so it holds nothing and becomes the new left wall: 2.
010210L13R2121left wall2right wall2water3left end lower → bar 4 holds 1
bar4height 1
left wall2
water3
The left end is shorter than the right end, so the right side already has a wall at least that tall. Bar 4 sits 1 below the left wall of height 2, so 1 unit of water stays on it.
0102101L3R2121left wall2right wall2water5left end lower → bar 5 holds 2
bar5height 0
left wall2
water5
The left end is shorter than the right end, so the right side already has a wall at least that tall. Bar 5 sits 2 below the left wall of height 2, so 2 units of water stay on it.
01021013L R2121left wall2right wall2water6left end lower → bar 6 holds 1
bar6height 1
left wall2
water6
The left end is shorter than the right end, so the right side already has a wall at least that tall. Bar 6 sits 1 below the left wall of height 2, so 1 unit of water stays on it.
010210132121left wall2right wall2water6pointers meet → 6 units trapped
answer6
The pointers meet on a tallest bar, which never holds water. Adding the water settled on each bar gives 6.
05

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.

▶1class Solution:
▶2 def trap(self, height):
▶3 n = len(height)
▶4 left = [0] * n
▶5 right = [0] * n
▶6 for i in range(n):
▶7 left[i] = max(left[i - 1] if i else 0, height[i])
▶8 for i in range(n - 1, -1, -1):
▶9 right[i] = max(right[i + 1] if i < n - 1 else 0, height[i])
▶10 return sum(min(left[i], right[i]) - height[i] for i in range(n))
06

Common pitfalls

Adding water before raising the maximum

✗ Wrong
water += left_max - height[l]
left_max = max(left_max, height[l])
✓ Right
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

✗ Wrong
top = max(height)
water = sum(top - h for h in height)
✓ Right
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.

07

Edge cases

Bars that only rise, or rise and then fall

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.

One or two bars

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.

08

Complexity

Time
O(n)
Space
O(1)
Each step moves one pointer inward by one, so the loop runs n - 1 times. Only four integers are kept, whatever the input size.
09

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.