# Longest Repeating Character Replacement

[link](https://leetcode.com/problems/longest-repeating-character-replacement/) · Medium · `string`, `hash map`, `sliding window`

> "longest substring that can be made uniform with ≤ k changes" → sliding window + letter counts, valid while windowlen - maxfreq <= k. More generally: turn the condition into a check that's O(1) to update as the window moves, then r adds, l removes, and you record r - l + 1. For longest problems the window can just slide (if, move l by one) instead of shrinking, and helpers like maxfreq never have to go down.

## Problem

> You are given a string `s` consisting of only uppercase English characters and an integer `k`.
> You can choose up to `k` characters of the string and replace them with any other uppercase English character.
>
> After performing at most `k` replacements, return the length of the **longest substring** which contains
> only one distinct character.

**Example 1**
```
Input:  s = "XYYX", k = 2
Output: 4
```
Either replace the `'X'`s with `'Y'`s, or replace the `'Y'`s with `'X'`s.

**Example 2**
```
Input:  s = "AAABABB", k = 1
Output: 5
```

**Constraints**
- `1 <= len(s) <= 100,000`
- `0 <= k <= len(s)`
- `s` consists of only uppercase English characters.

## Thinking

- **Brute force idea:** try every substring `s[i..j]`; it can be made uniform if the characters that are
  *not* its most frequent letter number at most `k`. Extending `j` with running counts gives $O(n^2)$, far too
  slow for $n = 100{,}000$.
- **Key insight:** a window can be made one letter iff **`window_len - max_freq <= k`** (keep the most
  frequent letter, replace everything else). This check is monotone: growing an invalid window keeps it
  invalid, shrinking a valid one keeps it valid. So use a **sliding window**: `r` adds one character per step,
  and when the window becomes invalid, move `l` right.
- **"Longest" means the window never has to shrink:** once a window of size `w` was valid, nothing smaller
  matters. So when it's invalid, move `l` by **one** (slide the window, size unchanged) instead of shrinking
  until it's valid. For the same reason `max_freq` never has to go *down* when `l` moves: a stale, too-high
  value can only keep the window from shrinking, and the answer only grows when some letter's count beats
  the old `max_freq`, and that new count is always real.
- **Another way to see it:** fix the letter you keep (26 choices). Then it's "longest window with at most `k`
  characters that aren't the target", which is Max Consecutive Ones III (#1004). $O(26 \cdot n)$, and no
  `max_freq` subtlety.
- **Edge cases to remember:** `k = 0` (→ the longest run of one letter); `k >= len(s)` (→ `len(s)`);
  a single character; all the same letter; all distinct (→ `min(len(s), k + 1)`); the best window
  is in the middle or at the very end; the best window shows up *after* a different letter was the most
  frequent (`"ABBBAAAA"`, `k = 1` → 5).

## Solution

### Approach A — mine: non-shrinking sliding window
**Complexity:** Time $O(26 \cdot n) = O(n)$ · Space $O(26)$

Correct, and already linear. It uses an `if`, not a `while`, so the window **never shrinks**: on every step it
either grows by one (valid, so `max_l` becomes its size) or slides right by one (invalid: add `s[r]`, drop `s[l]`).
That means `r - l + 1 == max_l` after every step, so the window being checked at `r` is exactly the
one candidate that could beat the answer. Because `max(c_dict.values())` is the real maximum, that check is
exact, and `continue` is safe: a slid window has the same size as `max_l`, so there's nothing to record.
Only polish is left: `max(c_dict.values())` rescans up to 26 counts on every character (a running `max_freq`
makes it $O(1)$), and `Counter` is imported but never used.

```python
from collections import Counter  # unused


def character_replacement_mine(s: str, k: int) -> int:
    c_dict = {}
    l = 0
    max_l = 0
    for r in range(len(s)):
        c_dict[s[r]] = 1 + c_dict.get(s[r], 0)

        if r - l + 1 - max(c_dict.values()) > k:  # max() scans up to 26 counts every step
            c_dict[s[l]] -= 1  # slide, don't shrink: the window keeps size max_l
            l += 1
            continue
        max_l = max(max_l, r - l + 1)

    return max_l
```

### Approach B — brute force: extend from every start
**Complexity:** Time $O(n^2)$ · Space $O(26)$

For each start `i`, extend `j` while keeping running counts and the running max, and record every valid
window. Obviously correct, so the tests use it as the reference on random strings. Way too slow for $n = 10^5$.

```python
def character_replacement_brute(s: str, k: int) -> int:
    best = 0
    for i in range(len(s)):
        count = {}
        max_freq = 0
        for j in range(i, len(s)):  # recounts the same characters for every i
            count[s[j]] = count.get(s[j], 0) + 1
            max_freq = max(max_freq, count[s[j]])
            if (j - i + 1) - max_freq <= k:
                best = max(best, j - i + 1)
    return best
```

### Approach C — fix the target letter (Max Consecutive Ones III, 26 times)
**Complexity:** Time $O(26 \cdot n)$ · Space $O(26)$

For each letter that appears, find the longest window with at most `k` characters that aren't that letter
(those are the ones you'd replace). There's no `max_freq` here, and the window is always valid, so it's the easiest
version to prove correct. The price is 26 passes over the string.

```python
def character_replacement_per_letter(s: str, k: int) -> int:
    best = 0
    for target in set(s):
        l = others = 0  # others = characters in the window that aren't target
        for r, c in enumerate(s):
            others += c != target
            while others > k:
                others -= s[l] != target
                l += 1
            best = max(best, r - l + 1)
    return best
```

### Approach D — sliding window + running `max_freq` ✅ best practice
**Complexity:** Time $O(n)$ · Space $O(26)$

The version to remember. Same window as A, but the most common count is updated in $O(1)$ when a character
comes in, and it is **never decreased** when one leaves (see Thinking: a stale value can't inflate the
answer). Because `max_freq` only gets bigger, the window is never more than one character over the limit, so the
`while` runs at most once and works exactly like A's `if`. It's written as `while` so it reads like every
other sliding window.

```python
def character_replacement(s: str, k: int) -> int:
    count = {}
    l = max_freq = best = 0
    for r, c in enumerate(s):
        count[c] = count.get(c, 0) + 1
        max_freq = max(max_freq, count[c])  # never decreased: a stale max can't inflate best
        while (r - l + 1) - max_freq > k:  # more than k to replace: move l (runs at most once)
            count[s[l]] -= 1
            l += 1
        best = max(best, r - l + 1)
    return best
```

## Scratch / Experiments

Input: a random string over all 26 letters at the max length $n = 100{,}000$ with `k = 100`, so A's
`max(c_dict.values())` really scans 26 counts and C really makes 26 passes. The brute force is $O(n^2)$ and
would take minutes at that size, so it runs on the first 2,000 characters only.

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.

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.

```python
rng = random.Random(0)
s = "".join(rng.choice(string.ascii_uppercase) for _ in range(100_000))
k = 100
small = s[:2_000]

assert character_replacement_mine(s, k) == character_replacement_per_letter(s, k) == character_replacement(s, k)
assert character_replacement_brute(small, k) == character_replacement(small, k)
%timeit character_replacement_mine(s, k)
%timeit character_replacement_per_letter(s, k)
%timeit character_replacement(s, k)
%timeit -n 1 -r 3 character_replacement_brute(small, k)
%timeit character_replacement(small, k)
```

## Takeaways

- **Pattern:** **"longest substring that can be made uniform with ≤ k changes" → sliding window + letter
  counts, valid while `window_len - max_freq <= k`.** More generally: turn the condition into a check that's
  $O(1)$ to update as the window moves, then `r` adds, `l` removes, and you record `r - l + 1`. For
  *longest* problems the window can just **slide** (`if`, move `l` by one) instead of shrinking, and helpers
  like `max_freq` never have to go down.
- **Mistakes I made:**
  - First attempt: looped over `l` and checked only `s[l:]`. Those are the $n$ substrings that **end at the
    last character**, so `"AAABA"` in example 2 was never tried (it returned 4, not 5). It also rebuilt a
    `Counter` for every start, which is $O(n^2)$. **A substring has two ends; if only one of them moves, you're
    missing candidates.**
  - Final version: correct and $O(n)$, but `max(c_dict.values())` rescans the counts every step. It's only
    cheap because the alphabet has 26 letters. Track `max_freq` as characters come in instead.
  - Left an unused `from collections import Counter`.
  - `if` + `continue` is right, but only because the window size equals `max_l` after every step. Know
    *why* it works (or write the `while` version) so you can defend it in an interview.
- **Related problems:** Max Consecutive Ones III (#1004, the one-target-letter version: at most `k` zeros);
  Maximize the Confusion of an Exam (#2024, this problem with only `'T'`/`'F'`); Longest Substring Without
  Repeating Characters (#3, same window shape, condition "no repeats"); Longest Substring with At Most K
  Distinct Characters (#340, count map + shrink); Permutation in String (#567, fixed-size window with counts);
  Minimum Window Substring (#76, the *shortest* version, where the window really must shrink).

---

From https://taosu.blog/notes/0424-longest-repeating-character-replacement
