{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "07b8b6b93e8a",
   "metadata": {},
   "source": [
    "# Trapping Rain Water\n",
    "\n",
    "| Field      | Value                                   |\n",
    "|------------|-----------------------------------------|\n",
    "| Source     | [link](https://leetcode.com/problems/trapping-rain-water/)  |\n",
    "| Difficulty | Hard                    |\n",
    "| Topics     | `array`, `two pointers`, `prefix max`, `monotonic stack`                     |\n",
    "| Date       | 2026-10-19                              |\n",
    "| Status     | Solved                                  |"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "144fac3609a1",
   "metadata": {},
   "source": [
    "## 1. Problem\n",
    "\n",
    "> You are given an array of non-negative integers `height` which represent an elevation map.\n",
    "> Each value `height[i]` represents the height of a bar, which has a width of 1.\n",
    "> Return the **total amount of water** that can be trapped between the bars.\n",
    "\n",
    "**Example 1**\n",
    "```\n",
    "Input:  height = [0,2,0,3,1,0,1,3,2,1]\n",
    "Output: 9\n",
    "```\n",
    "\n",
    "![Elevation map for [0,2,0,3,1,0,1,3,2,1] with 9 units of trapped water](data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSI1MDAiIGhlaWdodD0iMjIyIiB2aWV3Qm94PSIwIDAgNTAwIDIyMiIgZm9udC1mYW1pbHk9IkhlbHZldGljYSxBcmlhbCxzYW5zLXNlcmlmIj48cmVjdCB3aWR0aD0iNTAwIiBoZWlnaHQ9IjIyMiIgZmlsbD0iI2ZmZmZmZiIvPjx0ZXh0IHg9IjQwIiB5PSIyMCIgZm9udC1zaXplPSIxNCIgZmlsbD0iIzFmMjkzNyIgZm9udC13ZWlnaHQ9ImJvbGQiPmhlaWdodCA9IFswLDIsMCwzLDEsMCwxLDMsMiwxXSAg4oaSICB0cmFwcGVkIHdhdGVyID0gOTwvdGV4dD48bGluZSB4MT0iNDAiIHkxPSIxNjYiIHgyPSI0ODAiIHkyPSIxNjYiIHN0cm9rZT0iI2U1ZTdlYiIvPjx0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, tallest bar on the right)`:\n",
    "\n",
    "| i | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 |\n",
    "|---|---|---|---|---|---|---|---|---|---|---|\n",
    "| `height[i]` | 0 | 2 | 0 | 3 | 1 | 0 | 1 | 3 | 2 | 1 |\n",
    "| max on the left (incl. i) | 0 | 2 | 2 | 3 | 3 | 3 | 3 | 3 | 3 | 3 |\n",
    "| max on the right (incl. i) | 3 | 3 | 3 | 3 | 3 | 3 | 3 | 3 | 2 | 1 |\n",
    "| water = min(left, right) − height | 0 | 0 | **2** | 0 | **2** | **3** | **2** | 0 | 0 | 0 |\n",
    "\n",
    "Total `2 + 2 + 3 + 2 = 9`.\n",
    "\n",
    "**Example 2** (LeetCode's)\n",
    "```\n",
    "Input:  height = [4,2,0,3,2,5]\n",
    "Output: 9\n",
    "```\n",
    "\n",
    "**Constraints**\n",
    "- `1 <= len(height) <= 20000`\n",
    "- `0 <= height[i] <= 100000`"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3cfc0fbd224f",
   "metadata": {},
   "source": [
    "## 2. Thinking\n",
    "\n",
    "- **Think per column, not per pool.** The water above bar `i` is\n",
    "  `min(max(height[:i+1]), max(height[i:])) - height[i]`: it's held by the tallest wall on each\n",
    "  side, and the **shorter** of those two walls sets the level (look at index 5 in the picture:\n",
    "  walls of 3 on both sides → 3 units). The answer is the sum over all `i`.\n",
    "- **Brute force idea:** for every `i`, scan left and right for the two maxima. $O(n^2)$,\n",
    "  ~200 million steps at $n = 20000$.\n",
    "- **Precompute:** the left maxima are a prefix max (one pass left → right), the right maxima a\n",
    "  suffix max (one pass right → left). Then one more pass sums the water. $O(n)$ time,\n",
    "  $O(n)$ space.\n",
    "- **Key insight (two pointers, $O(1)$ space):** we don't need *both* maxima exactly, only the\n",
    "  smaller one. Keep `l`, `r` at both ends with the running maxima `l_max`, `r_max`. If\n",
    "  `height[l] < height[r]`, there is a wall on the right at least as tall as `height[r]`, which\n",
    "  is taller than everything the left side has seen so far, so for the next left column the level\n",
    "  is decided by `l_max` alone: water `= l_max - height[l]`. Move `l` inward. Symmetric for the\n",
    "  right. Each step settles one column → $O(n)$ time.\n",
    "- **Alternative (monotonic stack):** fill water in **horizontal layers**: keep a stack of\n",
    "  indices with decreasing heights; when a taller bar arrives, pop the bottom and fill the\n",
    "  rectangle between the new bar and the new stack top.\n",
    "- **Edge cases to remember:** `n = 1` or `n = 2` (no water possible); strictly increasing or\n",
    "  decreasing (0, no second wall); all zeros; flat plateaus (`[3,3,3]` → 0); a deep pool far\n",
    "  from the tallest bar (`[5,0,0,0,5]` → 15); the two end columns never hold water."
   ]
  },
  {
   "cell_type": "code",
   "id": "0f4a2ca29f02",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": [
    "# Setup: run this cell first. Lets you run pytest tests inside the notebook.\n",
    "try:\n",
    "    import ipytest\n",
    "except ImportError:  # Colab and other fresh kernels don't ship ipytest\n",
    "    %pip install -q ipytest\n",
    "    import ipytest\n",
    "import pytest\n",
    "\n",
    "ipytest.autoconfig()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "57c7d7cbd8ce",
   "metadata": {},
   "source": [
    "## 3. Solution\n",
    "\n",
    "### Approach A — mine: two pointers ✅ best practice\n",
    "**Complexity:** Time $O(n)$ · Space $O(1)$\n",
    "\n",
    "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."
   ]
  },
  {
   "cell_type": "code",
   "id": "b97bc32eb2bb",
   "metadata": {},
   "source": [
    "def trap_mine(height: list[int]) -> int:\n",
    "    l, r = 0, len(height) - 1\n",
    "    res = 0\n",
    "    l_max, r_max = height[l], height[r]\n",
    "\n",
    "    while l < r:\n",
    "        if height[l] < height[r]:  # right wall is taller -> left side's level is l_max\n",
    "            l += 1\n",
    "            l_max = max(height[l], l_max)\n",
    "            res += l_max - height[l]  # 0 when height[l] is the new max\n",
    "        else:\n",
    "            r -= 1\n",
    "            r_max = max(height[r], r_max)\n",
    "            res += r_max - height[r]\n",
    "    return res"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "id": "06cc24d49dcf",
   "metadata": {},
   "source": [
    "### Approach B — brute force, scan both sides for every column\n",
    "**Complexity:** Time $O(n^2)$ · Space $O(1)$\n",
    "\n",
    "The formula applied directly. Obviously correct, so the tests use it as a reference on random inputs; too slow at the real size."
   ]
  },
  {
   "cell_type": "code",
   "id": "d1f0d8992e1c",
   "metadata": {},
   "source": [
    "def trap_brute(height: list[int]) -> int:\n",
    "    total = 0\n",
    "    for i in range(len(height)):\n",
    "        left = max(height[: i + 1])  # O(n) scan for every i\n",
    "        right = max(height[i:])\n",
    "        total += min(left, right) - height[i]\n",
    "    return total"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "id": "563e62a19cbb",
   "metadata": {},
   "source": [
    "### Approach C — prefix max + suffix max arrays\n",
    "**Complexity:** Time $O(n)$ · Space $O(n)$\n",
    "\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."
   ]
  },
  {
   "cell_type": "code",
   "id": "7ca2120332fd",
   "metadata": {},
   "source": [
    "def trap_prefix(height: list[int]) -> int:\n",
    "    n = len(height)\n",
    "    left = [0] * n\n",
    "    right = [0] * n\n",
    "    left[0] = height[0]\n",
    "    for i in range(1, n):\n",
    "        left[i] = max(left[i - 1], height[i])\n",
    "    right[-1] = height[-1]\n",
    "    for i in range(n - 2, -1, -1):\n",
    "        right[i] = max(right[i + 1], height[i])\n",
    "    return sum(min(lm, rm) - h for lm, rm, h in zip(left, right, height))"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "id": "e1a082b67551",
   "metadata": {},
   "source": [
    "### Approach D — monotonic stack, fill horizontal layers\n",
    "**Complexity:** Time $O(n)$ · Space $O(n)$\n",
    "\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."
   ]
  },
  {
   "cell_type": "code",
   "id": "8ecb25cd3d95",
   "metadata": {},
   "source": [
    "def trap_stack(height: list[int]) -> int:\n",
    "    total = 0\n",
    "    stack = []  # indices, heights strictly decreasing from bottom to top\n",
    "    for i, h in enumerate(height):\n",
    "        while stack and height[stack[-1]] < h:\n",
    "            bottom = stack.pop()\n",
    "            if not stack:  # no left wall -> water spills out\n",
    "                break\n",
    "            left = stack[-1]\n",
    "            width = i - left - 1\n",
    "            level = min(height[left], h) - height[bottom]\n",
    "            total += width * level\n",
    "        stack.append(i)\n",
    "    return total"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "id": "096e347cb796",
   "metadata": {},
   "source": [
    "## 4. Tests\n",
    "\n",
    "All four approaches run against every case (the brute force is skipped at $n = 20000$); `test_random` compares A, C, D with the brute force on random small arrays."
   ]
  },
  {
   "cell_type": "code",
   "id": "7dbc8977baf4",
   "metadata": {},
   "source": [
    "%%ipytest -q\n",
    "import random\n",
    "\n",
    "N = 20000\n",
    "FNS = [trap_mine, trap_brute, trap_prefix, trap_stack]\n",
    "\n",
    "CASES = [\n",
    "    ([0, 2, 0, 3, 1, 0, 1, 3, 2, 1], 9),\n",
    "    ([4, 2, 0, 3, 2, 5], 9),           # LeetCode's example\n",
    "    ([5], 0),                          # minimum length\n",
    "    ([2, 7], 0),                       # two bars, nothing between them\n",
    "    ([0, 0, 0], 0),                    # all zeros\n",
    "    ([3, 3, 3], 0),                    # flat plateau\n",
    "    ([1, 2, 3, 4, 5], 0),              # increasing, no right wall\n",
    "    ([5, 4, 3, 2, 1], 0),              # decreasing, no left wall\n",
    "    ([3, 0, 3], 3),                    # single pool\n",
    "    ([5, 0, 0, 0, 5], 15),             # wide deep pool\n",
    "    ([4, 2, 3], 1),                    # lower right wall sets the level\n",
    "    ([2, 0, 2, 0, 2], 4),              # two pools, equal walls\n",
    "    ([2, 1, 0, 1, 3], 4),              # V shape, uneven walls\n",
    "    ([0, 100000, 0, 100000, 0], 100000),  # max height\n",
    "    ([100000] + [0] * (N - 2) + [100000], 100000 * (N - 2)),  # max length, one huge pool\n",
    "]\n",
    "\n",
    "\n",
    "@pytest.mark.parametrize(\"fn\", FNS)\n",
    "@pytest.mark.parametrize(\"height, expected\", CASES)\n",
    "def test_trap(fn, height, expected):\n",
    "    if fn is trap_brute and len(height) > 1000:\n",
    "        pytest.skip(\"O(n^2) is too slow at n = 20000\")\n",
    "    assert fn(height) == expected\n",
    "\n",
    "\n",
    "@pytest.mark.parametrize(\"seed\", range(200))\n",
    "def test_random(seed):\n",
    "    rng = random.Random(seed)\n",
    "    height = [rng.randint(0, 10) for _ in range(rng.randint(1, 30))]\n",
    "    expected = trap_brute(height)\n",
    "    for fn in FNS:\n",
    "        assert fn(height) == expected"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "id": "fef68b4a890e",
   "metadata": {},
   "source": [
    "## 5. Scratch / Experiments\n",
    "\n",
    "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.\n",
    "\n",
    "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$).\n",
    "\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."
   ]
  },
  {
   "cell_type": "code",
   "id": "4f48396afd97",
   "metadata": {},
   "source": [
    "rng = random.Random(0)\n",
    "height = [rng.randint(0, 100000) for _ in range(20000)]\n",
    "assert trap_mine(height) == trap_prefix(height) == trap_stack(height)\n",
    "%timeit trap_mine(height)\n",
    "%timeit trap_prefix(height)\n",
    "%timeit trap_stack(height)\n",
    "\n",
    "small = height[:2000]\n",
    "assert trap_brute(small) == trap_mine(small)\n",
    "%timeit -n 1 -r 3 trap_brute(small)\n",
    "%timeit trap_mine(small)"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "id": "c7096c786e6f",
   "metadata": {},
   "source": [
    "## 6. Takeaways\n",
    "\n",
    "- **Pattern:** **\"how much fits above each position\" → think per column: the answer at `i` is\n",
    "  `min(max to the left, max to the right) - height[i]`.** Needing \"max to the left/right\" for\n",
    "  every index → prefix/suffix max arrays. And when only the **smaller** of the two matters,\n",
    "  two pointers from both ends replace the arrays: move the side with the shorter bar, because\n",
    "  the taller side guarantees a wall at least that high.\n",
    "- **Mistakes I made:** none, this is the optimal $O(n)$ time / $O(1)$ space solution. Things to\n",
    "  keep in mind:\n",
    "  - Be ready to explain **why** `l_max` alone decides the left column's water when\n",
    "    `height[l] < height[r]` (the right side already has a wall taller than anything on the\n",
    "    left). That's the hard part of the problem.\n",
    "  - The order is \"move, update the max, then add\": updating the max first makes the added water\n",
    "    `>= 0` automatically, no `if` needed.\n",
    "  - If the two-pointer proof doesn't come to mind in an interview, the prefix/suffix version\n",
    "    (Approach C) is the safe fallback and is easy to prove.\n",
    "- **Related problems:** Container With Most Water (#11, same two pointers moving the shorter\n",
    "  side, but picks **one** pair instead of summing every column), Product of Array Except Self\n",
    "  (#238, the same prefix + suffix pass idea), Largest Rectangle in Histogram (#84, monotonic\n",
    "  stack over bars, like Approach D), Trapping Rain Water II (#407, the 2D version: min-heap from\n",
    "  the border inward), Pour Water (#755, simulation on an elevation map)."
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
