# Trapping Rain Water

[link](https://leetcode.com/problems/trapping-rain-water/) · Hard · `array`, `two pointers`, `prefix max`, `monotonic stack`

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

## 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](data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSI1MDAiIGhlaWdodD0iMjIyIiB2aWV3Qm94PSIwIDAgNTAwIDIyMiIgZm9udC1mYW1pbHk9IkhlbHZldGljYSxBcmlhbCxzYW5zLXNlcmlmIj48cmVjdCB3aWR0aD0iNTAwIiBoZWlnaHQ9IjIyMiIgZmlsbD0iI2ZmZmZmZiIvPjx0ZXh0IHg9IjQwIiB5PSIyMCIgZm9udC1zaXplPSIxNCIgZmlsbD0iIzFmMjkzNyIgZm9udC13ZWlnaHQ9ImJvbGQiPmhlaWdodCA9IFswLDIsMCwzLDEsMCwxLDMsMiwxXSAg4oaSICB0cmFwcGVkIHdhdGVyID0gOTwvdGV4dD48bGluZSB4MT0iNDAiIHkxPSIxNjYiIHgyPSI0ODAiIHkyPSIxNjYiIHN0cm9rZT0iI2U1ZTdlYiIvPjx0ZXh0IHg9IjMwIiB5PSIxNzAiIGZvbnQtc2l6ZT0iMTIiIGZpbGw9IiM2YjcyODAiIHRleHQtYW5jaG9yPSJlbmQiPjA8L3RleHQ+PGxpbmUgeDE9IjQwIiB5MT0iMTIyIiB4Mj0iNDgwIiB5Mj0iMTIyIiBzdHJva2U9IiNlNWU3ZWIiL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aG9yPSJtaWRkbGUiPjc8L3RleHQ+PHJlY3QgeD0iMzkyIiB5PSI3OCIgd2lkdGg9IjQ0IiBoZWlnaHQ9Ijg4IiBmaWxsPSIjNGI1NTYzIiBzdHJva2U9IiMxZjI5MzciIHN0cm9rZS13aWR0aD0iMSIvPjx0ZXh0IHg9IjQxNC4wIiB5PSIxODQiIGZvbnQtc2l6ZT0iMTIiIGZpbGw9IiM2YjcyODAiIHRleHQtYW5jaG9yPSJtaWRkbGUiPjg8L3RleHQ+PHJlY3QgeD0iNDM2IiB5PSIxMjIiIHdpZHRoPSI0NCIgaGVpZ2h0PSI0NCIgZmlsbD0iIzRiNTU2MyIgc3Ryb2tlPSIjMWYyOTM3IiBzdHJva2Utd2lkdGg9IjEiLz48dGV4dCB4PSI0NTguMCIgeT0iMTg0IiBmb250LXNpemU9IjEyIiBmaWxsPSIjNmI3MjgwIiB0ZXh0LWFuY2hvcj0ibWlkZGxlIj45PC90ZXh0PjxsaW5lIHgxPSI0MCIgeTE9IjE2NiIgeDI9IjQ4MCIgeTI9IjE2NiIgc3Ryb2tlPSIjMWYyOTM3IiBzdHJva2Utd2lkdGg9IjEuNSIvPjx0ZXh0IHg9IjI2MC4wIiB5PSIyMDIiIGZvbnQtc2l6ZT0iMTIiIGZpbGw9IiM2YjcyODAiIHRleHQtYW5jaG9yPSJtaWRkbGUiPmluZGV4IGkgICAoZ3JheSA9IGJhciwgYmx1ZSA9IHdhdGVyLCBudW1iZXIgPSB1bml0cyB0cmFwcGVkIGF0IGkpPC90ZXh0Pjwvc3ZnPg==)

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

| i | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 |
|---|---|---|---|---|---|---|---|---|---|---|
| `height[i]` | 0 | 2 | 0 | 3 | 1 | 0 | 1 | 3 | 2 | 1 |
| max on the left (incl. i) | 0 | 2 | 2 | 3 | 3 | 3 | 3 | 3 | 3 | 3 |
| max on the right (incl. i) | 3 | 3 | 3 | 3 | 3 | 3 | 3 | 3 | 2 | 1 |
| water = min(left, right) − height | 0 | 0 | **2** | 0 | **2** | **3** | **2** | 0 | 0 | 0 |

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(n^2)$,
  ~200 million steps at $n = 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)$ time,
  $O(n)$ space.
- **Key insight (two pointers, $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)$ 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)$ · Space $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.

```python
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(n^2)$ · Space $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.

```python
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)$ · Space $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)$ version to prove; two pointers is this with the arrays removed.

```python
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)$ · Space $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.

```python
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)$ approaches do the same amount of work on any input, so the input is just random heights at the max size ($n = 20000$). The brute force is timed at $n = 2000$ only.

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

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 $n$ 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.

```python
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)$ time / $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).

---

From https://taosu.blog/notes/0042-trapping-rain-water
