← HOME

Long. Repeating Char.

— sliding window with the "swap budget" check: size − max_count ≤ k.
String"AABABBA" k1 PatternSliding Window + max_count ComplexityO(n)
Step 0 of 0
Counts in window
empty
Validity check
window size
max_count
size − max_count
≤ k = 1?
Action
Press NEXT to begin
A 7-char string with k=1 swap. Watch how the window grows when valid and shrinks from the left when not.
Best window length so far 0

Why size − max_count ≤ k.

Inside any window, the most-common letter appears max_count times. Every other letter is something we'd have to swap to make the whole window the same letter.

So window_size − max_count = the number of "wrong" letters we'd need to replace. If that's ≤ k, the window is achievable within our swap budget. If not, shrink from the left.

The clever optimization: we never refresh max_count when the window shrinks. It can only go up across the whole run. A "stale" max_count just means the window stays open one or two extra steps — but the best we record is always achievable, because best ≤ max_count + k and max_count was set by a real window.

Net: each character is touched O(1) times by RIGHT (push) and O(1) times by LEFT (pop). Total O(n). The set-of-substrings brute force is O(n³).

Same shape carries over to: Longest Substring Without Repeating, Min Window Substring, Permutation in String.