Notes
All notes

Trapping Rain Water: the walls decide

Problem. Given n non-negative integers representing an elevation map where each bar has width 1, compute how much water it traps after raining.

height = [0,1,0,2,1,0,1,3,2,1,2,1]  →  6
\begin{tikzpicture}[x=0.6cm,y=0.62cm,
  b/.style={fill=black!10},
  w/.style={fill=cyan!35},
  e/.style={draw=black,thick}]
  \foreach \i/\ht/\wv in {0/0/0,1/1/1,2/0/1,3/2/2,4/1/2,5/0/2,6/1/2,7/3/3,8/2/2,9/1/2,10/2/2,11/1/1} {
    \fill[b] (\i,0) rectangle ++(1,\ht);
    \fill[w] (\i,\ht) rectangle ++(1,{\wv-\ht});
    \draw[e] (\i,0) rectangle ++(1,\ht);
  }
  \draw[e] (0,0) -- (12,0);
\end{tikzpicture}

The one idea

Water sitting on bar i is bounded by the tallest bar to its left and the tallest to its right — it can only rise as high as the shorter of those two walls:

\[ \text{water}[i] = \min(\text{maxLeft}[i],\ \text{maxRight}[i]) - \text{height}[i] \]

where maxLeft[i] is the tallest bar in height[0..i] and maxRight[i] the tallest in height[i..n-1]. Every solution below is just a different way to get those two walls.

Brute force

For each bar, scan left for the tallest wall and right for the tallest wall. That is \(O(n)\) per bar and \(O(n^2)\) overall, with \(O(1)\) extra space — fine for an interview warm-up, useless for \(n = 10^5\).

Precompute the walls

Two passes build both walls up front, then one pass adds up min(maxLeft[i], maxRight[i]) - height[i]. That is \(O(n)\) time and \(O(n)\) space. For height = [2,0,3,0,2]:

i 0 1 2 3 4
height 2 0 3 0 2
maxLeft 2 2 3 3 3
maxRight 3 3 3 2 2
min 2 2 3 2 2
water 0 2 0 2 0

Total: 4. (Column 0 is as tall as its left wall, and column 2 is the peak, so neither traps anything.)

Two pointers, O(1) space

We do not need both arrays at once. Walk inwards from both ends, keeping just a running leftMax and rightMax. At each step advance the pointer on the shorter side, because the taller side already guarantees a wall at least that high — so that bar’s water is decided by its own running max alone.

def trap(height):
    if not height:
        return 0
    left, right = 0, len(height) - 1
    left_max = right_max = 0
    water = 0
    while left < right:
        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 water

Dry run on [2, 0, 3, 0, 2]

Start. left = 0, right = 4, both walls are 0. Since height[0] = 2 is not less than height[4] = 2, the else branch runs: we process the right pointer first.

\begin{tikzpicture}[x=1.05cm,y=0.72cm,
  b/.style={fill=black!10}, w/.style={fill=cyan!35}, e/.style={draw=black,thick},
  p/.style={->,thick}, l/.style={font=\scriptsize\ttfamily}]
  \foreach \i/\ht in {0/2,1/0,2/3,3/0,4/2} { \fill[b] (\i,0) rectangle ++(1,\ht); }
  \foreach \i/\ht in {0/2,1/0,2/3,3/0,4/2} { \draw[e] (\i,0) rectangle ++(1,\ht); }
  \draw[e] (0,0) -- (5,0);
  \draw[p] (0.5,-0.8) -- (0.5,-0.15); \node[l] at (0.5,-1.05) {left};
  \draw[p] (4.5,-0.8) -- (4.5,-0.15); \node[l] at (4.5,-1.05) {right};
  \node[l,anchor=west] at (-0.1,3.6) {leftMax = 0};
  \node[l,anchor=east] at (5.1,3.6) {rightMax = 0};
  \node[l] at (2.5,3.6) {water = 0};
\end{tikzpicture}

After processing right = 4 and right = 3. The first move sets rightMax = 2 and adds nothing (bar 4 is its own wall). The second sets rightMax = 2 still, and bar 3 (height 0) traps 2 - 0 = 2. Now right = 2, and height[0] = 2 < height[2] = 3, so the left pointer takes over.

\begin{tikzpicture}[x=1.05cm,y=0.72cm,
  b/.style={fill=black!10}, w/.style={fill=cyan!35}, e/.style={draw=black,thick},
  p/.style={->,thick}, l/.style={font=\scriptsize\ttfamily}]
  \foreach \i/\ht in {0/2,1/0,2/3,3/0,4/2} { \fill[b] (\i,0) rectangle ++(1,\ht); }
  \fill[w] (3,0) rectangle ++(1,2);
  \foreach \i/\ht in {0/2,1/0,2/3,3/0,4/2} { \draw[e] (\i,0) rectangle ++(1,\ht); }
  \draw[e] (0,0) -- (5,0);
  \draw[p] (0.5,-0.8) -- (0.5,-0.15); \node[l] at (0.5,-1.05) {left};
  \draw[p] (2.5,-0.8) -- (2.5,-0.15); \node[l] at (2.5,-1.05) {right};
  \node[l,anchor=west] at (-0.1,3.6) {leftMax = 0};
  \node[l,anchor=east] at (5.1,3.6) {rightMax = 2};
  \node[l] at (2.5,3.6) {water = 2};
\end{tikzpicture}

Processing left = 0. height[0] = 2 becomes leftMax = 2, and bar 0 adds 2 - 2 = 0. The pointer moves to 1.

\begin{tikzpicture}[x=1.05cm,y=0.72cm,
  b/.style={fill=black!10}, w/.style={fill=cyan!35}, e/.style={draw=black,thick},
  p/.style={->,thick}, l/.style={font=\scriptsize\ttfamily}]
  \foreach \i/\ht in {0/2,1/0,2/3,3/0,4/2} { \fill[b] (\i,0) rectangle ++(1,\ht); }
  \fill[w] (3,0) rectangle ++(1,2);
  \foreach \i/\ht in {0/2,1/0,2/3,3/0,4/2} { \draw[e] (\i,0) rectangle ++(1,\ht); }
  \draw[e] (0,0) -- (5,0);
  \draw[p] (1.5,-0.8) -- (1.5,-0.15); \node[l] at (1.5,-1.05) {left};
  \draw[p] (2.5,-0.8) -- (2.5,-0.15); \node[l] at (2.5,-1.05) {right};
  \node[l,anchor=west] at (-0.1,3.6) {leftMax = 2};
  \node[l,anchor=east] at (5.1,3.6) {rightMax = 2};
  \node[l] at (2.5,3.6) {water = 2};
\end{tikzpicture}

Processing left = 1. height[1] = 0 is below leftMax = 2, so it traps 2 - 0 = 2, taking water to 4. left becomes 2, the two pointers meet, and the loop ends.

\begin{tikzpicture}[x=1.05cm,y=0.72cm,
  b/.style={fill=black!10}, w/.style={fill=cyan!35}, e/.style={draw=black,thick},
  p/.style={->,thick}, l/.style={font=\scriptsize\ttfamily}]
  \foreach \i/\ht in {0/2,1/0,2/3,3/0,4/2} { \fill[b] (\i,0) rectangle ++(1,\ht); }
  \fill[w] (1,0) rectangle ++(1,2);
  \fill[w] (3,0) rectangle ++(1,2);
  \foreach \i/\ht in {0/2,1/0,2/3,3/0,4/2} { \draw[e] (\i,0) rectangle ++(1,\ht); }
  \draw[e] (0,0) -- (5,0);
  \node[l,anchor=west] at (-0.1,3.6) {leftMax = 2};
  \node[l,anchor=east] at (5.1,3.6) {rightMax = 2};
  \node[l] at (2.5,3.6) {water = 4};
\end{tikzpicture}

Each bar is visited once, and neither wall array is ever stored.

The code in Go

func trap(height []int) int {
	left, right := 0, len(height)-1
	leftMax, rightMax, water := 0, 0, 0
	for left < right {
		if height[left] < height[right] {
			if height[left] > leftMax {
				leftMax = height[left]
			}
			water += leftMax - height[left]
			left++
		} else {
			if height[right] > rightMax {
				rightMax = height[right]
			}
			water += rightMax - height[right]
			right--
		}
	}
	return water
}

Complexity

Approach Time Extra space
Brute force \(O(n^2)\) \(O(1)\)
Precomputed walls \(O(n)\) \(O(n)\)
Two pointers \(O(n)\) \(O(1)\)

Edge cases

A monotonic stack is a fourth way to get \(O(n)\); it is a little harder to reason about but worth knowing since the same shape solves related problems such as Largest Rectangle in Histogram.