Skip to content
Back to notes
Oct 19, 2026
Hard

Trapping Rain Water

"how much fits above each position" → think per column: the answer at i is min(max to the left, max to the right) - height[i]. Needing "max to the left/right" for every index → prefix/suffix max arrays. And when only the smaller of the two matters, two pointers from both ends replace the arrays: move the side with the shorter bar, because the taller side guarantees a wall at least that high.
  • array
  • two pointers
  • prefix max
  • monotonic stack

Problem

You are given an array of non-negative integers height which represent an elevation map. Each value height[i] represents the height of a bar, which has a width of 1. Return the total amount of water that can be trapped between the bars.

Example 1

Input:  height = [0,2,0,3,1,0,1,3,2,1]
Output: 9

Elevation map for [0,2,0,3,1,0,1,3,2,1] with 9 units of trapped water

Water sits on top of bar i up to the level min(tallest bar on the left, tallest bar on the right):

i0123456789
height[i]0203101321
max on the left (incl. i)0223333333
max on the right (incl. i)3333333321
water = min(left, right) − height0020232000

Total 2 + 2 + 3 + 2 = 9.

Example 2 (LeetCode’s)

Input:  height = [4,2,0,3,2,5]
Output: 9

Constraints

  • 1 <= len(height) <= 20000
  • 0 <= height[i] <= 100000

Thinking

  • Think per column, not per pool. The water above bar i is min(max(height[:i+1]), max(height[i:])) - height[i]: it’s held by the tallest wall on each side, and the shorter of those two walls sets the level (look at index 5 in the picture: walls of 3 on both sides → 3 units). The answer is the sum over all i.
  • Brute force idea: for every i, scan left and right for the two maxima. O(n2)O(n^2), ~200 million steps at n=20000n = 20000.
  • Precompute: the left maxima are a prefix max (one pass left → right), the right maxima a suffix max (one pass right → left). Then one more pass sums the water. O(n)O(n) time, O(n)O(n) space.
  • Key insight (two pointers, O(1)O(1) space): we don’t need both maxima exactly, only the smaller one. Keep l, r at both ends with the running maxima l_max, r_max. If height[l] < height[r], there is a wall on the right at least as tall as height[r], which is taller than everything the left side has seen so far, so for the next left column the level is decided by l_max alone: water = l_max - height[l]. Move l inward. Symmetric for the right. Each step settles one column → O(n)O(n) time.
  • Alternative (monotonic stack): fill water in horizontal layers: keep a stack of indices with decreasing heights; when a taller bar arrives, pop the bottom and fill the rectangle between the new bar and the new stack top.
  • Edge cases to remember: n = 1 or n = 2 (no water possible); strictly increasing or decreasing (0, no second wall); all zeros; flat plateaus ([3,3,3] → 0); a deep pool far from the tallest bar ([5,0,0,0,5] → 15); the two end columns never hold water.

Solution

Approach A — mine: two pointers ✅ best practice

Complexity: Time O(n)O(n) · Space O(1)O(1)

Already optimal. Each step moves the pointer on the shorter side inward, updates that side’s running max and adds the water above the new column. Nothing slow in it: one pass, no extra arrays.

def trap_mine(height: list[int]) -> int:
    l, r = 0, len(height) - 1
    res = 0
    l_max, r_max = height[l], height[r]

    while l < r:
        if height[l] < height[r]:  # right wall is taller -> left side's level is l_max
            l += 1
            l_max = max(height[l], l_max)
            res += l_max - height[l]  # 0 when height[l] is the new max
        else:
            r -= 1
            r_max = max(height[r], r_max)
            res += r_max - height[r]
    return res

Approach B — brute force, scan both sides for every column

Complexity: Time O(n2)O(n^2) · Space O(1)O(1)

The formula applied directly. Obviously correct, so the tests use it as a reference on random inputs; too slow at the real size.

def trap_brute(height: list[int]) -> int:
    total = 0
    for i in range(len(height)):
        left = max(height[: i + 1])  # O(n) scan for every i
        right = max(height[i:])
        total += min(left, right) - height[i]
    return total

Approach C — prefix max + suffix max arrays

Complexity: Time O(n)O(n) · Space O(n)O(n)

Precompute the max on the left and on the right of every index (the two middle rows of the table in the problem), then sum min(left, right) - height. The easiest O(n)O(n) version to prove; two pointers is this with the arrays removed.

def trap_prefix(height: list[int]) -> int:
    n = len(height)
    left = [0] * n
    right = [0] * n
    left[0] = height[0]
    for i in range(1, n):
        left[i] = max(left[i - 1], height[i])
    right[-1] = height[-1]
    for i in range(n - 2, -1, -1):
        right[i] = max(right[i + 1], height[i])
    return sum(min(lm, rm) - h for lm, rm, h in zip(left, right, height))

Approach D — monotonic stack, fill horizontal layers

Complexity: Time O(n)O(n) · Space O(n)O(n)

A different view: instead of columns, fill the water layer by layer. The stack holds bars with decreasing heights (left walls waiting for a right wall). When a taller bar h arrives, pop the bottom; the water between the new stack top and i gets a layer width × (min(left wall, h) - bottom). Each index is pushed and popped once.

def trap_stack(height: list[int]) -> int:
    total = 0
    stack = []  # indices, heights strictly decreasing from bottom to top
    for i, h in enumerate(height):
        while stack and height[stack[-1]] < h:
            bottom = stack.pop()
            if not stack:  # no left wall -> water spills out
                break
            left = stack[-1]
            width = i - left - 1
            level = min(height[left], h) - height[bottom]
            total += width * level
        stack.append(i)
    return total

Scratch / Experiments

All O(n)O(n) approaches do the same amount of work on any input, so the input is just random heights at the max size (n=20000n = 20000). The brute force is timed at n=2000n = 2000 only.

Measured (one run): at n=20000n = 20000, mine (two pointers) ~1.6 ms, prefix/suffix arrays ~3.2 ms, monotonic stack ~3.7 ms. At n=2000n = 2000, brute force ~23 ms vs mine ~0.16 ms (~150×, and the gap grows linearly with nn).

Same Big-O, but two pointers is ~2× faster than the array versions: one pass with no list allocation, while C makes three passes and builds two lists of nn items, and D does a push + pop + several index lookups per bar. The brute force is “only” 150× slower because its inner scans are max() over a slice, which run in C; written as Python loops it would be far worse.

rng = random.Random(0)
height = [rng.randint(0, 100000) for _ in range(20000)]
assert trap_mine(height) == trap_prefix(height) == trap_stack(height)
%timeit trap_mine(height)
%timeit trap_prefix(height)
%timeit trap_stack(height)

small = height[:2000]
assert trap_brute(small) == trap_mine(small)
%timeit -n 1 -r 3 trap_brute(small)
%timeit trap_mine(small)

Takeaways

  • Pattern: “how much fits above each position” → think per column: the answer at i is min(max to the left, max to the right) - height[i]. Needing “max to the left/right” for every index → prefix/suffix max arrays. And when only the smaller of the two matters, two pointers from both ends replace the arrays: move the side with the shorter bar, because the taller side guarantees a wall at least that high.
  • Mistakes I made: none, this is the optimal O(n)O(n) time / O(1)O(1) space solution. Things to keep in mind:
    • Be ready to explain why l_max alone decides the left column’s water when height[l] < height[r] (the right side already has a wall taller than anything on the left). That’s the hard part of the problem.
    • The order is “move, update the max, then add”: updating the max first makes the added water >= 0 automatically, no if needed.
    • If the two-pointer proof doesn’t come to mind in an interview, the prefix/suffix version (Approach C) is the safe fallback and is easy to prove.
  • Related problems: Container With Most Water (#11, same two pointers moving the shorter side, but picks one pair instead of summing every column), Product of Array Except Self (#238, the same prefix + suffix pass idea), Largest Rectangle in Histogram (#84, monotonic stack over bars, like Approach D), Trapping Rain Water II (#407, the 2D version: min-heap from the border inward), Pour Water (#755, simulation on an elevation map).