mediumSliding WindowSliding Window

Longest Repeating Character Replacement

mediumTime: O(n)Space: O(1)

Signals to notice

longest substring with at most k character replacementsvariable window with budgettrack most frequent character

Brute force first

Check every substring. Each substring independently checked. That instinct is useful because it follows the prompt literally, but it usually keeps revisiting work the problem is begging you to organize.

The key insight

Sliding window: track the frequency of the most common character in the window. If windowSize - maxFreq > k, shrink from left. Track maximum window size. Once you hold onto the right piece of information from moment to moment, the problem feels less like trial and error and more like following a shape that was there all along.

What must stay true

A window is valid if the number of characters to replace (windowSize - maxFrequencyInWindow) ≤ k. The optimal strategy is to keep the most frequent character and replace the rest. When you keep that truth intact, each local choice supports the larger solution instead of fighting it.

Easy way to go wrong

Recalculating maxFreq from scratch when the window shrinks — you don't need to. An overestimate of maxFreq never causes wrong answers because the window only grows when maxFreq truly increases. When the code becomes mechanical before the idea is clear, small edge cases start breaking the whole story.

Sliding Window Pattern