{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "4e28e7b13485",
   "metadata": {},
   "source": [
    "# Permutation in String\n",
    "\n",
    "| Field      | Value                                   |\n",
    "|------------|-----------------------------------------|\n",
    "| Source     | [link](https://leetcode.com/problems/permutation-in-string/)  |\n",
    "| Difficulty | Medium                    |\n",
    "| Topics     | `string`, `hash map`, `sliding window`                     |\n",
    "| Date       | 2026-10-22                              |\n",
    "| Status     | Solved                                  |"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6aa72254565b",
   "metadata": {},
   "source": [
    "## 1. Problem\n",
    "\n",
    "> You are given two strings `s1` and `s2`.\n",
    ">\n",
    "> Return `true` if `s2` contains a **permutation** of `s1`, or `false` otherwise. That means if a permutation\n",
    "> of `s1` exists as a **substring** of `s2`, then return `true`.\n",
    ">\n",
    "> Both strings only contain lowercase letters.\n",
    "\n",
    "**Example 1**\n",
    "```\n",
    "Input:  s1 = \"abc\", s2 = \"lecabee\"\n",
    "Output: true\n",
    "```\n",
    "The substring `\"cab\"` is a permutation of `\"abc\"` and is present in `\"lecabee\"`.\n",
    "\n",
    "**Example 2**\n",
    "```\n",
    "Input:  s1 = \"abc\", s2 = \"lecaabee\"\n",
    "Output: false\n",
    "```\n",
    "\n",
    "**Constraints**\n",
    "- `1 <= len(s1), len(s2) <= 10,000`\n",
    "- Both strings consist of lowercase English letters."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "60cf23dc50de",
   "metadata": {},
   "source": [
    "## 2. Thinking\n",
    "\n",
    "- **Brute force idea:** generate every permutation of `s1` and search for it ($O(m!)$, hopeless), or check\n",
    "  every window of `s2` by sorting it ($O(n \\cdot m \\log m)$) or counting it ($O(n \\cdot m)$), where\n",
    "  $m = $ `len(s1)` and $n = $ `len(s2)`.\n",
    "- **Key insight:** \"a permutation of `s1`\" means **the same letter counts as `s1`**, and so the same length.\n",
    "  Only windows of exactly `m` characters can match, so this is a **fixed-size sliding window**. Moving the\n",
    "  window one step changes exactly two counts: `+1` for `s2[r]` coming in and `-1` for `s2[r - m]` going out.\n",
    "  Update those in $O(1)$ instead of recounting the window, then compare with `s1`'s counts: $O(26)$ with two\n",
    "  26-element arrays, or $O(1)$ if you keep a running count of how many letters the window is still missing.\n",
    "- **There are `n - m + 1` windows**, starting at `0 .. n - m`. A start past `n - m` gives a slice shorter\n",
    "  than `s1`, which can never match.\n",
    "- **Quick reject:** `len(s1) > len(s2)` means `False`.\n",
    "- **Edge cases to remember:** `s1` longer than `s2`; same length (the only window is all of `s2`); the match\n",
    "  at the very start or the very end (the last window must be checked); the right letters with the wrong\n",
    "  counts (example 2, `\"caab\"`); letters in `s2` that aren't in `s1`; a single character; repeated letters\n",
    "  in `s1`."
   ]
  },
  {
   "cell_type": "code",
   "id": "789ee1a13b72",
   "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": "65173580a2b3",
   "metadata": {},
   "source": [
    "## 3. Solution\n",
    "\n",
    "### Approach A — mine: recount every window with `Counter`\n",
    "**Complexity:** Time $O(n \\cdot m)$ · Space $O(m)$\n",
    "\n",
    "Correct, and the idea is right: compare letter counts, not orders. The cost is that it builds a new `Counter`\n",
    "from scratch for every start. `s2[l:r]` copies `m` characters and `Counter` reads all of them, even though\n",
    "the next window shares `m - 1` of them. The loop also runs `l` over all of `range(len(s2))`: for `l > n - m`\n",
    "the slice is shorter than `s1` and can never match. With `len(s1) == len(s2)` only the first window is real,\n",
    "and the other `n - 1` iterations recount about $n^2 / 2$ characters for nothing, which makes that the\n",
    "worst input (see Scratch). Small things: `r = 0` is never used, and `Counter(s1)` is built before the\n",
    "early return."
   ]
  },
  {
   "cell_type": "code",
   "id": "8d6aa48c2b47",
   "metadata": {},
   "source": [
    "from collections import Counter\n",
    "\n",
    "\n",
    "def check_inclusion_mine(s1: str, s2: str) -> bool:\n",
    "    count = Counter(s1)\n",
    "    if len(s1) > len(s2):\n",
    "        return False\n",
    "    r = 0  # unused: overwritten on the first iteration\n",
    "    for l in range(len(s2)):  # windows starting after len(s2) - len(s1) are too short to match\n",
    "        r = l + len(s1)\n",
    "        count_s2 = Counter(s2[l:r])  # O(m): copies and recounts the whole window every step\n",
    "\n",
    "        if count_s2 == count:\n",
    "            return True\n",
    "    return False"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "id": "52b0ec18466a",
   "metadata": {},
   "source": [
    "### Approach B — slide the `Counter` (smallest fix to A)\n",
    "**Complexity:** Time $O(26 \\cdot n)$ · Space $O(26)$\n",
    "\n",
    "Build the window's `Counter` once, then on each step add `s2[r]` and remove `s2[r - m]`. Removing can leave\n",
    "a key with count `0`; since Python 3.10, `Counter.__eq__` treats a zero count the same as a missing key, so\n",
    "the comparison still works (before 3.10 you had to `del` those keys). The catch: `Counter.__eq__` is written\n",
    "in Python (a generator over both key sets), so every comparison costs dozens of Python-level steps."
   ]
  },
  {
   "cell_type": "code",
   "id": "9685bed0554c",
   "metadata": {},
   "source": [
    "def check_inclusion_counter(s1: str, s2: str) -> bool:\n",
    "    m = len(s1)\n",
    "    if m > len(s2):\n",
    "        return False\n",
    "    need = Counter(s1)\n",
    "    window = Counter(s2[:m])\n",
    "    if window == need:\n",
    "        return True\n",
    "    for r in range(m, len(s2)):  # slide: s2[r] comes in, s2[r - m] goes out\n",
    "        window[s2[r]] += 1\n",
    "        window[s2[r - m]] -= 1  # may leave a 0 count; == ignores those (Python 3.10+)\n",
    "        if window == need:  # Python-level loop over the keys\n",
    "            return True\n",
    "    return False"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "id": "2535aec857a7",
   "metadata": {},
   "source": [
    "### Approach C — one count map + `missing` counter (true $O(n)$)\n",
    "**Complexity:** Time $O(n)$ · Space $O(26)$\n",
    "\n",
    "`need[c]` is how many more `c` the window needs (negative means it has extra), and `missing` is how many\n",
    "characters of `s1` the window doesn't cover yet. A character coming in lowers `missing` only if it was still\n",
    "needed; a character going out raises it only if it's needed again. When `missing == 0` the window has at\n",
    "least `s1`'s count of every letter and has length `m`, so it's exactly a permutation. Checking before the\n",
    "window is full is safe: `missing >= m - window_len > 0` there. No 26-way compare, so it works for any\n",
    "alphabet, and it's the same bookkeeping as Minimum Window Substring (#76). The follow-up answer if you're\n",
    "asked to drop the factor of 26."
   ]
  },
  {
   "cell_type": "code",
   "id": "ea796c14bf75",
   "metadata": {},
   "source": [
    "def check_inclusion_missing(s1: str, s2: str) -> bool:\n",
    "    m = len(s1)\n",
    "    if m > len(s2):\n",
    "        return False\n",
    "    need = Counter(s1)  # need[c] = how many more c the window needs (< 0: extra)\n",
    "    missing = m  # characters of s1 the window doesn't cover yet\n",
    "    for r, c in enumerate(s2):\n",
    "        if need[c] > 0:  # c was still needed\n",
    "            missing -= 1\n",
    "        need[c] -= 1\n",
    "        if r >= m:  # window is m + 1 long: drop s2[r - m]\n",
    "            out = s2[r - m]\n",
    "            need[out] += 1\n",
    "            if need[out] > 0:  # out is needed again\n",
    "                missing += 1\n",
    "        if missing == 0:  # length m and covers s1: a permutation\n",
    "            return True\n",
    "    return False"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "id": "166503f2c6f5",
   "metadata": {},
   "source": [
    "### Approach D — fixed-size window + two 26-count arrays ✅ best practice\n",
    "**Complexity:** Time $O(26 \\cdot n) = O(n)$ · Space $O(26)$\n",
    "\n",
    "The interview-standard version and the one to remember. Keep the counts in two fixed lists indexed by\n",
    "`ord(c) - ord(\"a\")`. Each step is two updates and one `window == need`. That list comparison runs in C and\n",
    "stops at the first count that differs, so it's the simplest version to write and also the fastest here,\n",
    "even though C has the better bound."
   ]
  },
  {
   "cell_type": "code",
   "id": "fe70d92fecfa",
   "metadata": {},
   "source": [
    "def check_inclusion(s1: str, s2: str) -> bool:\n",
    "    m, n = len(s1), len(s2)\n",
    "    if m > n:\n",
    "        return False\n",
    "    a = ord(\"a\")\n",
    "    need, window = [0] * 26, [0] * 26\n",
    "    for c in s1:\n",
    "        need[ord(c) - a] += 1\n",
    "    for c in s2[:m]:\n",
    "        window[ord(c) - a] += 1\n",
    "    if window == need:\n",
    "        return True\n",
    "    for r in range(m, n):  # slide: s2[r] comes in, s2[r - m] goes out\n",
    "        window[ord(s2[r]) - a] += 1\n",
    "        window[ord(s2[r - m]) - a] -= 1\n",
    "        if window == need:  # 26-element compare, runs in C\n",
    "            return True\n",
    "    return False"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "id": "8d4467d37bb7",
   "metadata": {},
   "source": [
    "## 4. Tests\n",
    "\n",
    "Every approach runs against every case; `test_random` compares all of them with a sort-every-window\n",
    "reference on random strings from a 3-letter alphabet (so matches are common)."
   ]
  },
  {
   "cell_type": "code",
   "id": "13d8132e8ede",
   "metadata": {},
   "source": [
    "%%ipytest -q\n",
    "import random\n",
    "\n",
    "FNS = [check_inclusion_mine, check_inclusion_counter, check_inclusion_missing, check_inclusion]\n",
    "\n",
    "CASES = [\n",
    "    (\"abc\", \"lecabee\", True),          # example 1: \"cab\"\n",
    "    (\"abc\", \"lecaabee\", False),        # example 2: \"caab\" has the letters but two a's\n",
    "    (\"ab\", \"eidbaooo\", True),          # LeetCode example 1\n",
    "    (\"ab\", \"eidboaoo\", False),         # LeetCode example 2: b and a never adjacent\n",
    "    (\"abc\", \"ab\", False),              # s1 longer than s2\n",
    "    (\"ab\", \"ba\", True),                # same length: the only window is all of s2\n",
    "    (\"ab\", \"aa\", False),               # same length, not a permutation\n",
    "    (\"a\", \"a\", True),                  # single characters\n",
    "    (\"a\", \"b\", False),                 # single character, missing\n",
    "    (\"abc\", \"cbaxyz\", True),           # match at the very start\n",
    "    (\"adc\", \"dcda\", True),             # match at the very end: \"cda\"\n",
    "    (\"aab\", \"abbb\", False),            # right letters, wrong counts\n",
    "    (\"aa\", \"aba\", False),              # repeated letter in s1, never adjacent\n",
    "    (\"hello\", \"ooolleoooleh\", False),  # every letter is present, never in one window\n",
    "]\n",
    "\n",
    "\n",
    "@pytest.mark.parametrize(\"fn\", FNS)\n",
    "@pytest.mark.parametrize(\"s1, s2, expected\", CASES)\n",
    "def test_check_inclusion(fn, s1, s2, expected):\n",
    "    assert fn(s1, s2) == expected\n",
    "\n",
    "\n",
    "def reference(s1, s2):  # sort every window: slow but obviously correct\n",
    "    m = len(s1)\n",
    "    return any(sorted(s2[i:i + m]) == sorted(s1) for i in range(len(s2) - m + 1))\n",
    "\n",
    "\n",
    "@pytest.mark.parametrize(\"seed\", range(300))\n",
    "def test_random(seed):\n",
    "    rng = random.Random(seed)\n",
    "    s1 = \"\".join(rng.choice(\"abc\") for _ in range(rng.randint(1, 5)))\n",
    "    s2 = \"\".join(rng.choice(\"abc\") for _ in range(rng.randint(1, 20)))\n",
    "    expected = reference(s1, s2)\n",
    "    for fn in FNS:\n",
    "        assert fn(s1, s2) == expected"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "id": "36bbfcefdba8",
   "metadata": {},
   "source": [
    "## 5. Scratch / Experiments\n",
    "\n",
    "Two inputs at the max length $n = 10{,}000$, neither with a match, so every approach scans to the end:\n",
    "- **`m = 5,000`**, random letters: $m = n/2$ is the most work for a correct `n - m + 1` loop\n",
    "  ($(n - m + 1) \\cdot m \\approx 25$ million characters counted).\n",
    "- **`m = n`**: `\"aaa…ab\"` in `\"aaa…a\"`. There's only one real window, so the sliding versions just count\n",
    "  each string once and stop, but A's loop keeps going over the shrinking tail.\n",
    "\n",
    "Measured (`m = 5,000`): two arrays (D) ~1.0 ms, `missing` counter (C) ~1.9 ms, sliding `Counter` (B) ~2.5 ms,\n",
    "mine (A) ~0.7 s (~700× slower than D). On `m = n`, A takes ~1 s against ~0.8 ms for D. That's *more* than\n",
    "on the first input even though there's only one real window: the `n - 1` too-short tail windows recount about\n",
    "$n^2 / 2 = 50$ million characters.\n",
    "\n",
    "D is $O(26 \\cdot n)$ and still beats C's $O(n)$ by about 2×. D's `window == need` is one C-level comparison that\n",
    "stops at the first count that differs (on random text that's within the first few letters), while C runs\n",
    "several Python-level operations per character for its `if`s and `Counter` lookups. B has the same bound as D,\n",
    "but `Counter.__eq__` is a Python generator, so it's the slowest of the sliding versions. A's per-character\n",
    "work is cheap (`Counter` counts in C), but ~37 million characters on the first input and ~50 million on the\n",
    "second still add up to most of a second. Big-O hides constants, and in Python the constant that matters is\n",
    "how many Python-level steps run per character."
   ]
  },
  {
   "cell_type": "code",
   "id": "1150cee05f89",
   "metadata": {},
   "source": [
    "import random\n",
    "import string\n",
    "\n",
    "rng = random.Random(0)\n",
    "s2 = \"\".join(rng.choice(string.ascii_lowercase) for _ in range(10_000))\n",
    "s1 = \"\".join(rng.choice(string.ascii_lowercase) for _ in range(5_000))\n",
    "same_s1, same_s2 = \"a\" * 9_999 + \"b\", \"a\" * 10_000  # len(s1) == len(s2), no match\n",
    "\n",
    "assert not any(fn(s1, s2) for fn in FNS)\n",
    "assert not any(fn(same_s1, same_s2) for fn in FNS)\n",
    "%timeit -n 1 -r 3 check_inclusion_mine(s1, s2)\n",
    "%timeit check_inclusion_counter(s1, s2)\n",
    "%timeit check_inclusion_missing(s1, s2)\n",
    "%timeit check_inclusion(s1, s2)\n",
    "%timeit -n 1 -r 3 check_inclusion_mine(same_s1, same_s2)\n",
    "%timeit check_inclusion(same_s1, same_s2)"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "id": "eed76f44928f",
   "metadata": {},
   "source": [
    "## 6. Takeaways\n",
    "\n",
    "- **Pattern:** **\"does `s2` contain a permutation / anagram of `s1`?\" → fixed-size sliding window of\n",
    "  `len(s1)` + letter counts.** \"Any order\" means compare counts; \"substring\" means a contiguous window of a\n",
    "  known length. When the window moves, one character comes in and one goes out: update those two counts and\n",
    "  **never recount the window**. Compare with a 26-element list `==`, or keep a `missing` counter for $O(1)$.\n",
    "- **Mistakes I made:**\n",
    "  - Rebuilt `Counter(s2[l:r])` for every window: $O(m)$ per step, $O(n \\cdot m)$ total, even though neighboring\n",
    "    windows share `m - 1` characters. **When a window moves by one, only two counts change.**\n",
    "  - Looped `l` over `range(len(s2))` instead of `range(len(s2) - len(s1) + 1)`. The last `len(s1) - 1`\n",
    "    windows are shorter than `s1` and can never match. With `len(s1) == len(s2)` that wasted tail is\n",
    "    the whole cost (about a second instead of under a millisecond). **A string of length `n` has `n - m + 1`\n",
    "    windows of length `m`.**\n",
    "  - Left a dead `r = 0`, and built `Counter(s1)` before the early return.\n",
    "- **Related problems:** Valid Anagram (#242, the one-window version: compare counts); Find All Anagrams in a\n",
    "  String (#438, this exact window, but collect every start index instead of returning `True`); Minimum Window\n",
    "  Substring (#76, the variable-size version of Approach C's `missing` counter); Longest Repeating Character\n",
    "  Replacement (#424, variable-size window with letter counts); Group Anagrams (#49, letter counts as a\n",
    "  dictionary key); Sliding Window Maximum (#239, fixed-size window with harder state to keep)."
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
