← Visualizers
Sliding Window · sub-variant D — the non-shrinking window LeetCode 424

Longest Repeating Character Replacement / visualized

Every other variable window shrinks. This one never does. When the window fails its test, l advances by exactly one in the same step that r advanced by one — so the width is preserved, never reduced, and the final width n − l is the answer. There is no best = max(…) line anywhere in the source. The test is width − maxCount ≤ k: the characters you would have to replace are everything that is not the most common one. And here is the part that looks like a bug and is not. maxCount is deliberately stale — it is the highest frequency ever seen, and it is never decreased when the window slides past the cell that produced it. A stale maxCount is always too large, which makes width − maxCount too small, so a stale window can look valid when it is not. That cannot hurt us: a falsely-valid window is never wider than the genuinely valid window that earned that maxCount in the first place, and since we only ever report the maximum width, an answer that is never larger than the truth and is achieved exactly once at the true optimum is simply the truth. Frames where the statistic has gone stale are marked below — watch that the width never moves backwards.

Execution

idle
s  ·  teal is the window, the amber underline is the cell that set maxCount
window width after each step — it never falls
Press Run to begin.
0 / 0
Speed

Java · running line

inside the window entering (cnt++) slid past (cnt−−) set maxCount left behind
O(n) time · O(26) space  ·  one pass, and l moves at most n times. Sub-variant D: the window slides instead of shrinking, so its width is monotone and no best variable is needed — s.length() - l is the answer by construction. maxCount being stale is the price of O(1) per step, and it is a price that provably cannot buy a wrong answer.