{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "4fbdb1500d0d",
   "metadata": {},
   "source": [
    "# Container With Most Water\n",
    "\n",
    "| Field      | Value                                   |\n",
    "|------------|-----------------------------------------|\n",
    "| Source     | [link](https://leetcode.com/problems/container-with-most-water/)  |\n",
    "| Difficulty | Medium                    |\n",
    "| Topics     | `array`, `two pointers`, `greedy`                     |\n",
    "| Date       | 2026-10-17                              |\n",
    "| Status     | Solved                                  |"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "244076b3cbb5",
   "metadata": {},
   "source": [
    "## 1. Problem\n",
    "\n",
    "> You are given an integer array `heights` where `heights[i]` is the height of the $i$-th bar.\n",
    "> You may choose any two bars to form a container. Return the **maximum amount of water** a\n",
    "> container can store.\n",
    "\n",
    "**Example 1**\n",
    "```\n",
    "Input:  height = [1,7,2,5,4,7,3,6]\n",
    "Output: 36\n",
    "```\n",
    "Bars at indices 1 and 7 (heights 7 and 6): width `7 - 1 = 6`, height `min(7, 6) = 6`,\n",
    "area `6 * 6 = 36`.\n",
    "\n",
    "**Example 2**\n",
    "```\n",
    "Input:  height = [2,2,2]\n",
    "Output: 4\n",
    "```\n",
    "\n",
    "**Constraints**\n",
    "- `2 <= len(height) <= 100000`\n",
    "- `0 <= height[i] <= 10000`"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7b80c419bb86",
   "metadata": {},
   "source": [
    "## 2. Thinking\n",
    "\n",
    "- **Brute force idea:** try every pair `i < j`, area = `(j - i) * min(h[i], h[j])`, keep the max.\n",
    "  $O(n^2)$, ~5 billion pairs at $n = 100000$, so too slow.\n",
    "- **Key insight:** start with the **widest** container (`l = 0`, `r = n - 1`) and always move the\n",
    "  **shorter** side inward. Why that's safe: say `h[l] <= h[r]`. Every other container that uses\n",
    "  `l` pairs it with some `r' < r`. It's narrower, and its height is still at most `h[l]`\n",
    "  (the water level is capped by the shorter bar). So none of them can beat the current area, and\n",
    "  bar `l` can be dropped for good. Moving the taller side instead could never help: the width\n",
    "  shrinks and the height stays capped by the same short bar. Each step drops one bar →\n",
    "  $O(n)$ time, $O(1)$ space.\n",
    "- **Edge cases to remember:** `n = 2` (only one container); zero heights (area 0);\n",
    "  equal heights (moving either side is fine); the best pair isn't the two tallest bars\n",
    "  (`[1,7,2,5,4,7,3,6]` → 7 and 6, not 7 and 7, because the width matters)."
   ]
  },
  {
   "cell_type": "code",
   "id": "da8323023133",
   "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": "17d9afd613fa",
   "metadata": {},
   "source": [
    "## 3. Solution\n",
    "\n",
    "### Approach A — my version: two pointers, move the shorter side ✅ best practice\n",
    "**Complexity:** Time $O(n)$ · Space $O(1)$\n",
    "\n",
    "Already optimal. Compute the area at each step, then move the pointer at the shorter bar.\n",
    "On a tie it moves `l`, which is fine: when `h[l] == h[r]`, no container using either bar can\n",
    "beat the current one, so either can be dropped."
   ]
  },
  {
   "cell_type": "code",
   "id": "d3298c29249a",
   "metadata": {},
   "source": [
    "def max_area_mine(heights: list[int]) -> int:\n",
    "    l = 0\n",
    "    r = len(heights) - 1\n",
    "    max_area = 0\n",
    "    while l < r:\n",
    "        max_area = max(max_area, (r - l) * min(heights[l], heights[r]))\n",
    "        if heights[l] > heights[r]:\n",
    "            r -= 1\n",
    "        else:  # shorter (or equal) bar on the left -> drop it\n",
    "            l += 1\n",
    "\n",
    "    return max_area"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "id": "17c3a8f0c198",
   "metadata": {},
   "source": [
    "### Approach B — brute force, every pair\n",
    "**Complexity:** Time $O(n^2)$ · Space $O(1)$\n",
    "\n",
    "Checks every pair. Obviously correct, so the tests use it as a reference on random inputs, but\n",
    "it times out at the real constraint size."
   ]
  },
  {
   "cell_type": "code",
   "id": "3595a1d4d0f6",
   "metadata": {},
   "source": [
    "def max_area_brute(heights: list[int]) -> int:\n",
    "    n = len(heights)\n",
    "    best = 0\n",
    "    for i in range(n - 1):\n",
    "        for j in range(i + 1, n):\n",
    "            best = max(best, (j - i) * min(heights[i], heights[j]))\n",
    "    return best"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "id": "afe3c5f41cb9",
   "metadata": {},
   "source": [
    "### Approach C — two pointers, skip bars that can't help\n",
    "**Complexity:** Time $O(n)$ · Space $O(1)$\n",
    "\n",
    "Same algorithm, constant-factor speedup. After computing an area with water level\n",
    "`level = min(h[l], h[r])`, every bar that is not taller than `level` can be skipped without\n",
    "computing its area: it's narrower **and** no taller, so it can't beat the area just recorded.\n",
    "The inner `while` loops are cheap compared with `max`/`min` calls."
   ]
  },
  {
   "cell_type": "code",
   "id": "82bb60bef523",
   "metadata": {},
   "source": [
    "def max_area_skip(heights: list[int]) -> int:\n",
    "    l, r = 0, len(heights) - 1\n",
    "    best = 0\n",
    "    while l < r:\n",
    "        level = min(heights[l], heights[r])\n",
    "        best = max(best, (r - l) * level)\n",
    "        while l < r and heights[l] <= level:  # narrower and no taller -> can't win\n",
    "            l += 1\n",
    "        while l < r and heights[r] <= level:\n",
    "            r -= 1\n",
    "    return best"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "id": "f40293d5422c",
   "metadata": {},
   "source": [
    "## 4. Tests\n",
    "\n",
    "All three approaches run against every case; `test_random` compares A and C with the\n",
    "brute force on random small arrays."
   ]
  },
  {
   "cell_type": "code",
   "id": "d3445d36700d",
   "metadata": {},
   "source": [
    "%%ipytest -q\n",
    "import random\n",
    "\n",
    "N = 100000\n",
    "\n",
    "CASES = [\n",
    "    ([1, 7, 2, 5, 4, 7, 3, 6], 36),\n",
    "    ([2, 2, 2], 4),\n",
    "    ([1, 8, 6, 2, 5, 4, 8, 3, 7], 49),  # LeetCode's example\n",
    "    ([1, 1], 1),                        # minimum length\n",
    "    ([0, 0], 0),                        # zero heights\n",
    "    ([0, 5], 0),                        # one zero bar -> no water\n",
    "    ([4, 3, 2, 1, 4], 16),              # the two ends, inner bars are lower\n",
    "    ([1, 2, 1], 2),                     # the tallest bar isn't enough alone\n",
    "    ([1, 2, 4, 3], 4),                  # best pair is in the middle-right\n",
    "    ([10000, 10000], 10000),            # max height\n",
    "    (list(range(1, 11)), 25),           # increasing: 5 * 5 (bars 5 and 10)\n",
    "    ([10000] * N, 10000 * (N - 1)),     # max length, all equal: the two ends\n",
    "]\n",
    "\n",
    "\n",
    "@pytest.mark.parametrize(\"fn\", [max_area_mine, max_area_brute, max_area_skip])\n",
    "@pytest.mark.parametrize(\"heights, expected\", CASES)\n",
    "def test_max_area(fn, heights, expected):\n",
    "    if fn is max_area_brute and len(heights) > 1000:\n",
    "        pytest.skip(\"O(n^2) is too slow at n = 100000\")\n",
    "    assert fn(heights) == expected\n",
    "\n",
    "\n",
    "@pytest.mark.parametrize(\"seed\", range(200))\n",
    "def test_random(seed):\n",
    "    rng = random.Random(seed)\n",
    "    heights = [rng.randint(0, 10) for _ in range(rng.randint(2, 30))]\n",
    "    expected = max_area_brute(heights)\n",
    "    assert max_area_mine(heights) == expected\n",
    "    assert max_area_skip(heights) == expected"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "id": "3499bd215d9b",
   "metadata": {},
   "source": [
    "## 5. Scratch / Experiments\n",
    "\n",
    "The two-pointer versions always do about $n$ steps, so the input is just random heights at the\n",
    "max size ($n = 100000$). The brute force is timed at $n = 2000$ only (~2 million pairs).\n",
    "\n",
    "Measured (one run): at $n = 100000$, mine ~9.1 ms, with skipping ~2.9 ms. At $n = 2000$,\n",
    "brute force ~136 ms vs mine ~0.19 ms (~700×, and the gap grows linearly with $n$).\n",
    "The skip version is ~3× faster with the same Big-O: on random heights most inner bars are\n",
    "shorter than the current water level, so they're passed over with one comparison each, instead\n",
    "of a multiply plus the `max()`/`min()` function calls, which are slow in Python."
   ]
  },
  {
   "cell_type": "code",
   "id": "9844f112acdd",
   "metadata": {},
   "source": [
    "rng = random.Random(0)\n",
    "heights = [rng.randint(0, 10000) for _ in range(100000)]\n",
    "assert max_area_mine(heights) == max_area_skip(heights)\n",
    "%timeit max_area_mine(heights)\n",
    "%timeit max_area_skip(heights)\n",
    "\n",
    "small = heights[:2000]\n",
    "assert max_area_brute(small) == max_area_mine(small)\n",
    "%timeit -n 1 -r 3 max_area_brute(small)\n",
    "%timeit max_area_mine(small)"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "id": "e847fb0c9b44",
   "metadata": {},
   "source": [
    "## 6. Takeaways\n",
    "\n",
    "- **Pattern:** **best pair where the value depends on the width (distance) and the smaller\n",
    "  of the two → two pointers from both ends, move the limiting side.** Start as wide as possible;\n",
    "  each step gives up width, so the only hope is a taller limiting bar, so throw away the shorter\n",
    "  one. The proof idea to remember: *the shorter bar has already had its best container\n",
    "  (the widest one), so drop it.*\n",
    "- **Mistakes I made:** none, it's the optimal solution. Things to keep in mind:\n",
    "  - Be ready to explain **why** moving the shorter side never skips the answer. That's what an\n",
    "    interviewer will ask.\n",
    "  - A tie can move either pointer.\n",
    "  - Micro-optimization: after computing an area, skip all bars no taller than the current water\n",
    "    level (Approach C).\n",
    "- **Related problems:** Trapping Rain Water (#42, also two pointers from both ends moving the\n",
    "  shorter side, but it sums the water above every bar instead of picking one pair),\n",
    "  Two Sum II (#167, two pointers from both ends on a sorted array), 3Sum (#15, sort + two pointers),\n",
    "  Largest Rectangle in Histogram (#84, area limited by the shortest bar, solved with a monotonic stack),\n",
    "  Valid Palindrome (#125, two pointers moving inward)."
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
