codebrew.ai

Longest Repeating Character Replacement

A window is valid while (length − count of its most frequent char) ≤ k.

Approach

Slide a window tracking character counts and the max single-character count inside it. If the window's length minus that max exceeds k, too many replacements are needed — shrink from the left. The widest valid window is the answer.

Time complexity

O(n)

Space complexity

O(1)

Common mistake

Recomputing the true max frequency on every shrink; you can let a slightly stale max stand because the window only ever needs to grow past its best.

See it run, step by step

Generate an interactive lesson for Longest Repeating Character Replacement — trace every variable and watch the algorithm execute until it clicks.

Start a lesson on Longest Repeating Character Replacement

Related problems