← Back to Algorithms, page 1

algorithms-0019 · Hard senior

Trapping rain water: given bar heights, compute how many units of water are trapped after rain.

Water above bar i equals min(max height to its left, max height to its right) minus its own height. Prefix and suffix maximum arrays give O(n) time and O(n) space. Two pointers reach O(1) space: move the side with the lower bar, because its water level is already decided by that side's running maximum.

Full answer

Problem

Given heights of bars with width 1, return the total units of water trapped between them.

Example: [0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1] gives 6.

Constraints: 0 <= len(heights) <= 2 x 10^4, heights from 0 to 10^5.

Brute force

For each bar, scan left for the highest bar and right for the highest bar; add min(left_max, right_max) - height. O(n^2).

Better: prefix and suffix maxima

Precompute left_max[i] and right_max[i] in two passes, then sum min(left_max[i], right_max[i]) - heights[i]. O(n) time, O(n) space.

Optimal: two pointers

Keep lo, hi, left_max and right_max.

  • If heights[lo] < heights[hi]: update left_max, add left_max - heights[lo], move lo right.
  • Otherwise: update right_max, add right_max - heights[hi], move hi left.

Why it works

The left pointer only moves when its bar is lower than the bar at hi, and hi is to its right. So every bar the left pointer has passed, including the current one, is lower than some bar to the right of lo. That means left_max is lower than the tallest bar on the right, and the water level at lo, which is min(left side max, right side max), is exactly left_max. The mirror argument covers the right pointer (with "lower or equal"). Each position is finalised once.

A third view: monotonic stack

Keep a stack of indices with decreasing heights. When a taller bar arrives, pop a bar and fill the "valley" between the new bar and the bar now on top of the stack, layer by layer. Also O(n) time and O(n) space; useful to know because it computes water by horizontal layers.

Complexity

Two pointers: O(n) time, O(1) space.

Code

python
def trap(heights):
    """Units of rain water trapped. Two pointers, O(n) time, O(1) extra space."""
    lo, hi = 0, len(heights) - 1
    left_max = right_max = 0
    water = 0
    while lo < hi:
        if heights[lo] < heights[hi]:
            left_max = max(left_max, heights[lo])
            water += left_max - heights[lo]      # right side is at least as tall
            lo += 1
        else:
            right_max = max(right_max, heights[hi])
            water += right_max - heights[hi]
            hi -= 1
    return water


def trap_brute(heights):
    total = 0
    for i in range(len(heights)):
        level = min(max(heights[:i + 1]), max(heights[i:]))
        total += level - heights[i]
    return total


if __name__ == "__main__":
    for f in (trap, trap_brute):
        assert f([0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1]) == 6
        assert f([4, 2, 0, 3, 2, 5]) == 9
        assert f([]) == 0
        assert f([3]) == 0
        assert f([1, 2, 3]) == 0
        assert f([3, 0, 3]) == 3
    print("all tests passed")

Save as a19_trapping_rain.py and run python3 a19_trapping_rain.py. It prints all tests passed (Python 3.13.5).

Edge cases

Empty input, one or two bars (no water). Strictly increasing or decreasing bars (no water). Plateaus with equal heights. A deep single valley like [3, 0, 3] (3 units).

Pattern

Prefix and suffix extremes, optimised to two pointers. The same "level is set by the smaller of two maxima" reasoning appears in 2D as trapping rain water II, solved with a min-heap from the borders.

python
def trap(heights):
    """Units of rain water trapped. Two pointers, O(n) time, O(1) extra space."""
    lo, hi = 0, len(heights) - 1
    left_max = right_max = 0
    water = 0
    while lo < hi:
        if heights[lo] < heights[hi]:
            left_max = max(left_max, heights[lo])
            water += left_max - heights[lo]      # right side is at least as tall
            lo += 1
        else:
            right_max = max(right_max, heights[hi])
            water += right_max - heights[hi]
            hi -= 1
    return water


def trap_brute(heights):
    total = 0
    for i in range(len(heights)):
        level = min(max(heights[:i + 1]), max(heights[i:]))
        total += level - heights[i]
    return total


if __name__ == "__main__":
    for f in (trap, trap_brute):
        assert f([0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1]) == 6
        assert f([4, 2, 0, 3, 2, 5]) == 9
        assert f([]) == 0
        assert f([3]) == 0
        assert f([1, 2, 3]) == 0
        assert f([3, 0, 3]) == 3
    print("all tests passed")

Two-pointer solution with O(1) space; an O(n^2) brute force is checked against it.

Complexity

Time: O(n). Space: O(1). The prefix/suffix array version is also O(n) time but uses O(n) space.

By level

Fresher: Explains the per-bar formula with the brute force and the prefix/suffix arrays version. Should explain the water level at a single position.

Mid: Implements the two-pointer version and justifies moving the lower side. Tests flat, increasing and V-shaped inputs.

Senior: Also explains the monotonic stack approach and the heap-based 2D generalisation, and compares their trade-offs. Mentions the 2D version, which needs a heap.

Key points

  • Water at i = min(left max, right max) - height[i]
  • Prefix and suffix maxima give O(n) time, O(n) space
  • Two pointers move the lower side and reach O(1) space
  • The lower side's level is already determined
  • A monotonic stack computes water by layers

Common mistakes

  • Using max instead of min of the two sides
  • Moving the taller pointer
  • Adding negative water when the bar is the new maximum
  • Confusing with container with most water

Follow-ups

  • Explain the monotonic stack version
  • How would you solve the 2D version on a grid?
  • How would you compute water if bars have different widths?

Tips

  • State the per-bar formula first
  • Give the prefix/suffix solution before the two-pointer one
  • Explain why the lower side is safe to finalise

Evaluation rubric

  • Correct formula and O(n) algorithm
  • Correct justification for two pointers
  • Handles edge cases
  • Knows an alternative method