{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "520e0cfcebac",
   "metadata": {},
   "source": [
    "# Longest Substring Without Repeating Characters\n",
    "\n",
    "| Field      | Value                                   |\n",
    "|------------|-----------------------------------------|\n",
    "| Source     | [link](https://leetcode.com/problems/longest-substring-without-repeating-characters/)  |\n",
    "| Difficulty | Medium                    |\n",
    "| Topics     | `string`, `hash set`, `hash map`, `sliding window`                     |\n",
    "| Date       | 2026-10-20                              |\n",
    "| Status     | Solved                                  |"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "766b751c7e58",
   "metadata": {},
   "source": [
    "## 1. Problem\n",
    "\n",
    "> Given a string `s`, find the length of the **longest substring** without duplicate characters.\n",
    "> A **substring** is a contiguous sequence of characters within a string.\n",
    "\n",
    "**Example 1**\n",
    "```\n",
    "Input:  s = \"zxyzxyz\"\n",
    "Output: 3\n",
    "```\n",
    "The string `\"xyz\"` is the longest without duplicate characters.\n",
    "\n",
    "**Example 2**\n",
    "```\n",
    "Input:  s = \"xxxx\"\n",
    "Output: 1\n",
    "```\n",
    "\n",
    "**Constraints**\n",
    "- `0 <= len(s) <= 50,000`\n",
    "- `s` may consist of printable ASCII characters."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8ad1a9201b93",
   "metadata": {},
   "source": [
    "## 2. Thinking\n",
    "\n",
    "- **Brute force idea:** for every start `i`, extend to the right with a hash set until a\n",
    "  character repeats, and keep the longest run. $O(n \\cdot \\sigma)$, where $\\sigma$ is the alphabet\n",
    "  size (a run can't be longer than $\\sigma$), so $O(n^2)$ when the alphabet is unbounded.\n",
    "- **Key insight:** when the brute force restarts at `i + 1`, it re-checks characters it already\n",
    "  knows are distinct. Instead keep a **window** `[l, r]` that is always duplicate-free: `r` advances one\n",
    "  step at a time, and when `s[r]` is already in the window, move `l` right (removing `s[l]` from the set)\n",
    "  until it isn't. Each character enters and leaves the window at most once → $O(n)$.\n",
    "- **Faster shrink:** remember the **last index** of every character. On a repeat, `l` can jump straight\n",
    "  to `last[c] + 1`, with no inner loop. Guard it with `max(l, ...)`: an old index that is already left of `l`\n",
    "  must not move the window backwards.\n",
    "- **Edge cases to remember:** empty string (→ 0); all the same character (`\"xxxx\"` → 1); all distinct\n",
    "  (→ `len(s)`); the repeat is **not** at the window's left end (`\"dvdf\"` → 3: keep `\"v\"`, drop only the first\n",
    "  `\"d\"`); the duplicate is the character just before `r` (`\"abccd\"` → 3); a character last seen *before* `l`\n",
    "  (`\"abba\"` → 2: the old `a` must not pull `l` back); spaces and punctuation count as characters."
   ]
  },
  {
   "cell_type": "code",
   "id": "4441cedabff8",
   "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": "3918da81e170",
   "metadata": {},
   "source": [
    "## 3. Solution\n",
    "\n",
    "### Approach A — mine: sliding window + hash set\n",
    "**Complexity:** Time $O(n)$ · Space $O(\\min(n, \\sigma))$\n",
    "\n",
    "Already optimal in Big-O. Each iteration does the same three steps: **shrink** (remove `s[l]` and advance `l` while `s[r]` is still in the window), **add** `s[r]`, **update** the best length. The inner `while` doesn't make it $O(n^2)$: every character is added once and removed at most once, so the total work is $2n$. Polish only: starting `max_l` at `0` makes the `if not s` guard unnecessary."
   ]
  },
  {
   "cell_type": "code",
   "id": "2d3de99f41bc",
   "metadata": {},
   "source": [
    "def length_of_longest_substring_mine(s: str) -> int:\n",
    "    if not s:  # unnecessary if max_l starts at 0\n",
    "        return 0\n",
    "    l, max_l = 0, 1\n",
    "    s_set = set()\n",
    "\n",
    "    for r in range(len(s)):\n",
    "        while s[r] in s_set:  # shrink until s[r] can join; amortised O(1) per character\n",
    "            s_set.remove(s[l])\n",
    "            l += 1\n",
    "        s_set.add(s[r])\n",
    "        max_l = max(max_l, r - l + 1)\n",
    "\n",
    "    return max_l"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "id": "a0feb4b35c94",
   "metadata": {},
   "source": [
    "### Approach B — brute force: extend from every start\n",
    "**Complexity:** Time $O(n \\cdot \\sigma)$ · Space $O(\\sigma)$\n",
    "\n",
    "For each start, grow a run until the first repeat. Obviously correct, so the tests use it as the reference on random strings. With only ~95 printable characters each run is short, so it's less hopeless than $O(n^2)$, but it still re-scans the same characters over and over."
   ]
  },
  {
   "cell_type": "code",
   "id": "eb98a33944f3",
   "metadata": {},
   "source": [
    "def length_of_longest_substring_brute(s: str) -> int:\n",
    "    best = 0\n",
    "    for i in range(len(s)):\n",
    "        seen = set()\n",
    "        for c in s[i:]:  # restarts from scratch for every i\n",
    "            if c in seen:\n",
    "                break\n",
    "            seen.add(c)\n",
    "        best = max(best, len(seen))\n",
    "    return best"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "id": "bf86c25fe5c1",
   "metadata": {},
   "source": [
    "### Approach C — sliding window + last-index map ✅ best practice\n",
    "**Complexity:** Time $O(n)$ · Space $O(\\min(n, \\sigma))$\n",
    "\n",
    "The version to remember. Same window as A, but the dict stores where each character was **last seen**, so on a repeat `l` jumps straight past it instead of walking there one step at a time. Characters are never removed from the dict; the `>= l` check ignores entries that are already outside the window (that's the `\"abba\"` trap)."
   ]
  },
  {
   "cell_type": "code",
   "id": "1fdf5ab65883",
   "metadata": {},
   "source": [
    "def length_of_longest_substring(s: str) -> int:\n",
    "    last = {}  # char -> index where it was last seen\n",
    "    l = best = 0\n",
    "    for r, c in enumerate(s):\n",
    "        if last.get(c, -1) >= l:  # repeat inside the window: jump past it\n",
    "            l = last[c] + 1\n",
    "        last[c] = r\n",
    "        best = max(best, r - l + 1)\n",
    "    return best"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "id": "0738190d40c8",
   "metadata": {},
   "source": [
    "## 4. Tests\n",
    "\n",
    "Every approach runs against every case; `test_random` compares all of them with the brute force on random strings from a small alphabet (so repeats are frequent)."
   ]
  },
  {
   "cell_type": "code",
   "id": "e30b9e9da440",
   "metadata": {},
   "source": [
    "%%ipytest -q\n",
    "import random\n",
    "import string\n",
    "\n",
    "FNS = [length_of_longest_substring_mine, length_of_longest_substring_brute, length_of_longest_substring]\n",
    "\n",
    "CASES = [\n",
    "    (\"zxyzxyz\", 3),        # example 1\n",
    "    (\"xxxx\", 1),           # example 2, all the same character\n",
    "    (\"\", 0),               # empty string\n",
    "    (\"a\", 1),              # single character\n",
    "    (\"abcabcbb\", 3),       # LeetCode's example\n",
    "    (\"pwwkew\", 3),         # answer is a substring, not a subsequence (\"pwke\" doesn't count)\n",
    "    (\"dvdf\", 3),           # repeat at the window's left end: keep \"v\"\n",
    "    (\"abccd\", 3),          # duplicate right before r: shrink past two characters\n",
    "    (\"abcdeafghij\", 10),   # the old \"a\" must leave the set when l passes it\n",
    "    (\"abba\", 2),           # last-seen index before l must not pull l back\n",
    "    (\"tmmzuxt\", 5),        # same trap, longer\n",
    "    (\"a b!a\", 4),          # spaces and punctuation are characters too\n",
    "    (string.printable[:95], 95),  # every printable character once\n",
    "]\n",
    "\n",
    "\n",
    "@pytest.mark.parametrize(\"fn\", FNS)\n",
    "@pytest.mark.parametrize(\"s, expected\", CASES)\n",
    "def test_length_of_longest_substring(fn, s, expected):\n",
    "    assert fn(s) == expected\n",
    "\n",
    "\n",
    "@pytest.mark.parametrize(\"seed\", range(200))\n",
    "def test_random(seed):\n",
    "    rng = random.Random(seed)\n",
    "    s = \"\".join(rng.choice(\"abcde \") for _ in range(rng.randint(0, 60)))\n",
    "    expected = length_of_longest_substring_brute(s)\n",
    "    for fn in FNS:\n",
    "        assert fn(s) == expected"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "id": "78225ff939ff",
   "metadata": {},
   "source": [
    "## 5. Scratch / Experiments\n",
    "\n",
    "Worst case for the brute force: the 95 printable characters repeated in a cycle up to the max length $n = 50{,}000$, so every start scans a full run of 95 before hitting a repeat. A random string is also timed, where runs are short and the brute force looks much better than it is.\n",
    "\n",
    "Measured ($n = 50{,}000$): on the cyclic string, last-index map ~4.6 ms, mine ~5.9 ms, brute force ~183 ms (~30× slower). On the random string, map ~3.9 ms, mine ~7.0 ms, brute force ~55 ms.\n",
    "\n",
    "Both windows are $O(n)$, but the map version is consistently faster: it does one dict lookup and one store per character, while the set version also does a `remove` + `l += 1` for every character that leaves the window (up to $2n$ set operations in total). The brute force is only ~10–30× slower rather than thousands of times, because $\\sigma \\approx 95$ caps every run; with an unbounded alphabet it would be truly $O(n^2)$."
   ]
  },
  {
   "cell_type": "code",
   "id": "07cae6e8fccf",
   "metadata": {},
   "source": [
    "chars = string.printable[:95]\n",
    "cyclic = (chars * (50_000 // len(chars) + 1))[:50_000]\n",
    "rng = random.Random(0)\n",
    "random_s = \"\".join(rng.choice(chars) for _ in range(50_000))\n",
    "\n",
    "for s in (cyclic, random_s):\n",
    "    assert length_of_longest_substring_mine(s) == length_of_longest_substring(s) == length_of_longest_substring_brute(s)\n",
    "    %timeit length_of_longest_substring_mine(s)\n",
    "    %timeit length_of_longest_substring(s)\n",
    "    %timeit -n 1 -r 3 length_of_longest_substring_brute(s)"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "id": "87895f574f8d",
   "metadata": {},
   "source": [
    "## 6. Takeaways\n",
    "\n",
    "- **Pattern:** **\"longest contiguous run where a condition holds\" → sliding window.** `r` always advances;\n",
    "  when adding `s[r]` would break the condition, shrink from the left until it holds again; then record\n",
    "  `r - l + 1`. Every element enters and leaves once, so the nested `while` is still $O(n)$. If you can compute\n",
    "  *where* `l` must go (here: one past the last copy of `s[r]`), jump there directly with a last-index map.\n",
    "- **Mistakes I made** (in earlier drafts, before the final version):\n",
    "  - Changing `r` inside `for r in range(...)` (`r + 1`, `r = l + 1`, `r += 1`): the `for` overwrites it\n",
    "    on the next iteration, so it does nothing or only works by accident. Compute lengths from `r` and `l` instead.\n",
    "  - Never removing characters from the set when `l` moved, so characters outside the window still counted\n",
    "    as duplicates. **The set must hold exactly the window.**\n",
    "  - Removing `s[r]` instead of `s[l]`: the character that leaves when `l` moves is the one on the **left**.\n",
    "  - Moving `l` by one step (or jumping to `r`) instead of **until the duplicate is gone** → use a `while`.\n",
    "  - Splitting the loop into `if` / `else` and forgetting to add `s[r]` and update the answer in the `else`.\n",
    "    The fix was one shape for every iteration: **shrink → add → update**.\n",
    "  - Tests that only cover the examples pass by luck: `\"dvdf\"`, `\"abccd\"` and `\"abba\"` are the cases that\n",
    "    actually exercise the shrink.\n",
    "- **Related problems:** Best Time to Buy and Sell Stock (#121, the simpler window where `l` jumps on a new low);\n",
    "  Longest Repeating Character Replacement (#424, window valid while `len - max_count <= k`); Permutation in\n",
    "  String (#567) and Find All Anagrams (#438, fixed-size window with counts); Minimum Window Substring (#76,\n",
    "  the \"shortest\" version: grow until valid, then shrink); Longest Substring with At Most K Distinct\n",
    "  Characters (#340, same shape with a count map)."
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
