{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "7716ff175857",
   "metadata": {},
   "source": [
    "# Longest Repeating Character Replacement\n",
    "\n",
    "| Field      | Value                                   |\n",
    "|------------|-----------------------------------------|\n",
    "| Source     | [link](https://leetcode.com/problems/longest-repeating-character-replacement/)  |\n",
    "| Difficulty | Medium                    |\n",
    "| Topics     | `string`, `hash map`, `sliding window`                     |\n",
    "| Date       | 2026-10-21                              |\n",
    "| Status     | Solved                                  |"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "05552781e99f",
   "metadata": {},
   "source": [
    "## 1. Problem\n",
    "\n",
    "> You are given a string `s` consisting of only uppercase English characters and an integer `k`.\n",
    "> You can choose up to `k` characters of the string and replace them with any other uppercase English character.\n",
    ">\n",
    "> After performing at most `k` replacements, return the length of the **longest substring** which contains\n",
    "> only one distinct character.\n",
    "\n",
    "**Example 1**\n",
    "```\n",
    "Input:  s = \"XYYX\", k = 2\n",
    "Output: 4\n",
    "```\n",
    "Either replace the `'X'`s with `'Y'`s, or replace the `'Y'`s with `'X'`s.\n",
    "\n",
    "**Example 2**\n",
    "```\n",
    "Input:  s = \"AAABABB\", k = 1\n",
    "Output: 5\n",
    "```\n",
    "\n",
    "**Constraints**\n",
    "- `1 <= len(s) <= 100,000`\n",
    "- `0 <= k <= len(s)`\n",
    "- `s` consists of only uppercase English characters."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e0eff9852cfe",
   "metadata": {},
   "source": [
    "## 2. Thinking\n",
    "\n",
    "- **Brute force idea:** try every substring `s[i..j]`; it can be made uniform if the characters that are\n",
    "  *not* its most frequent letter number at most `k`. Extending `j` with running counts gives $O(n^2)$, far too\n",
    "  slow for $n = 100{,}000$.\n",
    "- **Key insight:** a window can be made one letter iff **`window_len - max_freq <= k`** (keep the most\n",
    "  frequent letter, replace everything else). This check is monotone: growing an invalid window keeps it\n",
    "  invalid, shrinking a valid one keeps it valid. So use a **sliding window**: `r` adds one character per step,\n",
    "  and when the window becomes invalid, move `l` right.\n",
    "- **\"Longest\" means the window never has to shrink:** once a window of size `w` was valid, nothing smaller\n",
    "  matters. So when it's invalid, move `l` by **one** (slide the window, size unchanged) instead of shrinking\n",
    "  until it's valid. For the same reason `max_freq` never has to go *down* when `l` moves: a stale, too-high\n",
    "  value can only keep the window from shrinking, and the answer only grows when some letter's count beats\n",
    "  the old `max_freq`, and that new count is always real.\n",
    "- **Another way to see it:** fix the letter you keep (26 choices). Then it's \"longest window with at most `k`\n",
    "  characters that aren't the target\", which is Max Consecutive Ones III (#1004). $O(26 \\cdot n)$, and no\n",
    "  `max_freq` subtlety.\n",
    "- **Edge cases to remember:** `k = 0` (→ the longest run of one letter); `k >= len(s)` (→ `len(s)`);\n",
    "  a single character; all the same letter; all distinct (→ `min(len(s), k + 1)`); the best window\n",
    "  is in the middle or at the very end; the best window shows up *after* a different letter was the most\n",
    "  frequent (`\"ABBBAAAA\"`, `k = 1` → 5)."
   ]
  },
  {
   "cell_type": "code",
   "id": "c8a1c1cc1a32",
   "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": "e2329b4be86e",
   "metadata": {},
   "source": [
    "## 3. Solution\n",
    "\n",
    "### Approach A — mine: non-shrinking sliding window\n",
    "**Complexity:** Time $O(26 \\cdot n) = O(n)$ · Space $O(26)$\n",
    "\n",
    "Correct, and already linear. It uses an `if`, not a `while`, so the window **never shrinks**: on every step it\n",
    "either grows by one (valid, so `max_l` becomes its size) or slides right by one (invalid: add `s[r]`, drop `s[l]`).\n",
    "That means `r - l + 1 == max_l` after every step, so the window being checked at `r` is exactly the\n",
    "one candidate that could beat the answer. Because `max(c_dict.values())` is the real maximum, that check is\n",
    "exact, and `continue` is safe: a slid window has the same size as `max_l`, so there's nothing to record.\n",
    "Only polish is left: `max(c_dict.values())` rescans up to 26 counts on every character (a running `max_freq`\n",
    "makes it $O(1)$), and `Counter` is imported but never used."
   ]
  },
  {
   "cell_type": "code",
   "id": "0bf659065e93",
   "metadata": {},
   "source": [
    "from collections import Counter  # unused\n",
    "\n",
    "\n",
    "def character_replacement_mine(s: str, k: int) -> int:\n",
    "    c_dict = {}\n",
    "    l = 0\n",
    "    max_l = 0\n",
    "    for r in range(len(s)):\n",
    "        c_dict[s[r]] = 1 + c_dict.get(s[r], 0)\n",
    "\n",
    "        if r - l + 1 - max(c_dict.values()) > k:  # max() scans up to 26 counts every step\n",
    "            c_dict[s[l]] -= 1  # slide, don't shrink: the window keeps size max_l\n",
    "            l += 1\n",
    "            continue\n",
    "        max_l = max(max_l, r - l + 1)\n",
    "\n",
    "    return max_l"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "id": "077deba28b4d",
   "metadata": {},
   "source": [
    "### Approach B — brute force: extend from every start\n",
    "**Complexity:** Time $O(n^2)$ · Space $O(26)$\n",
    "\n",
    "For each start `i`, extend `j` while keeping running counts and the running max, and record every valid\n",
    "window. Obviously correct, so the tests use it as the reference on random strings. Way too slow for $n = 10^5$."
   ]
  },
  {
   "cell_type": "code",
   "id": "dc14e0a6d67e",
   "metadata": {},
   "source": [
    "def character_replacement_brute(s: str, k: int) -> int:\n",
    "    best = 0\n",
    "    for i in range(len(s)):\n",
    "        count = {}\n",
    "        max_freq = 0\n",
    "        for j in range(i, len(s)):  # recounts the same characters for every i\n",
    "            count[s[j]] = count.get(s[j], 0) + 1\n",
    "            max_freq = max(max_freq, count[s[j]])\n",
    "            if (j - i + 1) - max_freq <= k:\n",
    "                best = max(best, j - i + 1)\n",
    "    return best"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "id": "ce3b35c18f73",
   "metadata": {},
   "source": [
    "### Approach C — fix the target letter (Max Consecutive Ones III, 26 times)\n",
    "**Complexity:** Time $O(26 \\cdot n)$ · Space $O(26)$\n",
    "\n",
    "For each letter that appears, find the longest window with at most `k` characters that aren't that letter\n",
    "(those are the ones you'd replace). There's no `max_freq` here, and the window is always valid, so it's the easiest\n",
    "version to prove correct. The price is 26 passes over the string."
   ]
  },
  {
   "cell_type": "code",
   "id": "3c8a46c9cb5a",
   "metadata": {},
   "source": [
    "def character_replacement_per_letter(s: str, k: int) -> int:\n",
    "    best = 0\n",
    "    for target in set(s):\n",
    "        l = others = 0  # others = characters in the window that aren't target\n",
    "        for r, c in enumerate(s):\n",
    "            others += c != target\n",
    "            while others > k:\n",
    "                others -= s[l] != target\n",
    "                l += 1\n",
    "            best = max(best, r - l + 1)\n",
    "    return best"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "id": "461665a48169",
   "metadata": {},
   "source": [
    "### Approach D — sliding window + running `max_freq` ✅ best practice\n",
    "**Complexity:** Time $O(n)$ · Space $O(26)$\n",
    "\n",
    "The version to remember. Same window as A, but the most common count is updated in $O(1)$ when a character\n",
    "comes in, and it is **never decreased** when one leaves (see Thinking: a stale value can't inflate the\n",
    "answer). Because `max_freq` only gets bigger, the window is never more than one character over the limit, so the\n",
    "`while` runs at most once and works exactly like A's `if`. It's written as `while` so it reads like every\n",
    "other sliding window."
   ]
  },
  {
   "cell_type": "code",
   "id": "bd66fbf77142",
   "metadata": {},
   "source": [
    "def character_replacement(s: str, k: int) -> int:\n",
    "    count = {}\n",
    "    l = max_freq = best = 0\n",
    "    for r, c in enumerate(s):\n",
    "        count[c] = count.get(c, 0) + 1\n",
    "        max_freq = max(max_freq, count[c])  # never decreased: a stale max can't inflate best\n",
    "        while (r - l + 1) - max_freq > k:  # more than k to replace: move l (runs at most once)\n",
    "            count[s[l]] -= 1\n",
    "            l += 1\n",
    "        best = max(best, r - l + 1)\n",
    "    return best"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "id": "f83ba7c3517d",
   "metadata": {},
   "source": [
    "## 4. Tests\n",
    "\n",
    "Every approach runs against every case; `test_random` compares all of them with the brute force on random\n",
    "strings from a 3-letter alphabet (so windows with mixed letters are common) and random `k`."
   ]
  },
  {
   "cell_type": "code",
   "id": "7fb5f4dcacbd",
   "metadata": {},
   "source": [
    "%%ipytest -q\n",
    "import random\n",
    "import string\n",
    "\n",
    "FNS = [character_replacement_mine, character_replacement_brute, character_replacement_per_letter, character_replacement]\n",
    "\n",
    "CASES = [\n",
    "    (\"XYYX\", 2, 4),       # example 1\n",
    "    (\"AAABABB\", 1, 5),    # example 2: best window \"AAABA\" ends before the last character\n",
    "    (\"ABAB\", 2, 4),       # LeetCode example 1\n",
    "    (\"AABABBA\", 1, 4),    # LeetCode example 2\n",
    "    (\"A\", 0, 1),          # single character\n",
    "    (\"AAAA\", 0, 4),       # all the same letter, no replacements needed\n",
    "    (\"ABAB\", 0, 1),       # k = 0: longest run of one letter\n",
    "    (\"AABBBCCCC\", 0, 4),  # k = 0, the longest run is at the end\n",
    "    (\"ABCDE\", 5, 5),      # k >= len(s): the whole string\n",
    "    (\"ABCDE\", 1, 2),      # all distinct: k + 1\n",
    "    (\"BAAAB\", 2, 5),      # replace both ends\n",
    "    (\"ABBBAAAA\", 1, 5),   # best window comes after B was the most frequent letter\n",
    "    (\"ABCBBBCAB\", 1, 5),  # best window in the middle\n",
    "]\n",
    "\n",
    "\n",
    "@pytest.mark.parametrize(\"fn\", FNS)\n",
    "@pytest.mark.parametrize(\"s, k, expected\", CASES)\n",
    "def test_character_replacement(fn, s, k, expected):\n",
    "    assert fn(s, k) == expected\n",
    "\n",
    "\n",
    "@pytest.mark.parametrize(\"seed\", range(300))\n",
    "def test_random(seed):\n",
    "    rng = random.Random(seed)\n",
    "    s = \"\".join(rng.choice(\"ABC\") for _ in range(rng.randint(1, 40)))\n",
    "    k = rng.randint(0, len(s))\n",
    "    expected = character_replacement_brute(s, k)\n",
    "    for fn in FNS:\n",
    "        assert fn(s, k) == expected"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "id": "643aaf3ca91a",
   "metadata": {},
   "source": [
    "## 5. Scratch / Experiments\n",
    "\n",
    "Input: a random string over all 26 letters at the max length $n = 100{,}000$ with `k = 100`, so A's\n",
    "`max(c_dict.values())` really scans 26 counts and C really makes 26 passes. The brute force is $O(n^2)$ and\n",
    "would take minutes at that size, so it runs on the first 2,000 characters only.\n",
    "\n",
    "Measured ($n = 100{,}000$): running `max_freq` (D) ~19 ms, mine (A) ~32 ms, fix-the-letter (C) ~300 ms. On the 2,000-character prefix the brute force takes ~217 ms against ~0.37 ms for D (~600× slower). It grows with $n^2$, so at full size it would take about 2,500× longer, around 9 minutes.\n",
    "\n",
    "A is only ~1.6× slower than D even though it rescans up to 26 counts every step: `max(c_dict.values())` runs in C, so 26 comparisons cost about as much as a couple of Python-level operations. C has the same $O(n)$ bound, but its constant is 26 passes of a *Python* loop, which is why it is ~16× slower. Big-O hides constants, and in Python the constant that matters is how many Python-level steps run per character."
   ]
  },
  {
   "cell_type": "code",
   "id": "0cb77d03941c",
   "metadata": {},
   "source": [
    "rng = random.Random(0)\n",
    "s = \"\".join(rng.choice(string.ascii_uppercase) for _ in range(100_000))\n",
    "k = 100\n",
    "small = s[:2_000]\n",
    "\n",
    "assert character_replacement_mine(s, k) == character_replacement_per_letter(s, k) == character_replacement(s, k)\n",
    "assert character_replacement_brute(small, k) == character_replacement(small, k)\n",
    "%timeit character_replacement_mine(s, k)\n",
    "%timeit character_replacement_per_letter(s, k)\n",
    "%timeit character_replacement(s, k)\n",
    "%timeit -n 1 -r 3 character_replacement_brute(small, k)\n",
    "%timeit character_replacement(small, k)"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "id": "fbf7663a2853",
   "metadata": {},
   "source": [
    "## 6. Takeaways\n",
    "\n",
    "- **Pattern:** **\"longest substring that can be made uniform with ≤ k changes\" → sliding window + letter\n",
    "  counts, valid while `window_len - max_freq <= k`.** More generally: turn the condition into a check that's\n",
    "  $O(1)$ to update as the window moves, then `r` adds, `l` removes, and you record `r - l + 1`. For\n",
    "  *longest* problems the window can just **slide** (`if`, move `l` by one) instead of shrinking, and helpers\n",
    "  like `max_freq` never have to go down.\n",
    "- **Mistakes I made:**\n",
    "  - First attempt: looped over `l` and checked only `s[l:]`. Those are the $n$ substrings that **end at the\n",
    "    last character**, so `\"AAABA\"` in example 2 was never tried (it returned 4, not 5). It also rebuilt a\n",
    "    `Counter` for every start, which is $O(n^2)$. **A substring has two ends; if only one of them moves, you're\n",
    "    missing candidates.**\n",
    "  - Final version: correct and $O(n)$, but `max(c_dict.values())` rescans the counts every step. It's only\n",
    "    cheap because the alphabet has 26 letters. Track `max_freq` as characters come in instead.\n",
    "  - Left an unused `from collections import Counter`.\n",
    "  - `if` + `continue` is right, but only because the window size equals `max_l` after every step. Know\n",
    "    *why* it works (or write the `while` version) so you can defend it in an interview.\n",
    "- **Related problems:** Max Consecutive Ones III (#1004, the one-target-letter version: at most `k` zeros);\n",
    "  Maximize the Confusion of an Exam (#2024, this problem with only `'T'`/`'F'`); Longest Substring Without\n",
    "  Repeating Characters (#3, same window shape, condition \"no repeats\"); Longest Substring with At Most K\n",
    "  Distinct Characters (#340, count map + shrink); Permutation in String (#567, fixed-size window with counts);\n",
    "  Minimum Window Substring (#76, the *shortest* version, where the window really must shrink)."
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
