Given a string s and integer k, return the length of the longest substring containing the same letter after replacing at most k characters.
s = "ABAB", k = 24s = "AABABBA", k = 14l = 0, maxFreq = 0, maxLen = 0, freq[26]r: expand window — increment freq[s[r]], update maxFreq(r−l+1) − maxFreq > k → shrink: decrement freq[s[l]], l++maxLen = max(maxLen, r−l+1) — track best valid windowmaxLenIn any window, windowSize − maxFreq is the minimum replacements needed to make every character the same (keep the dominant letter, change the rest). If that exceeds k, the window is invalid — slide l right once. Each r only moves forward, and l only catches up, so the scan is O(n). maxFreq only increases (an optimization); the window may temporarily be invalid before shrinking, but maxLen records the largest valid window ever seen.
Trying every substring and every letter is very expensive. We want one pass.
In a window, keep the most frequent letter, and change the rest. So the changes needed are the window length minus the max frequency. If that is more than k, the window is invalid. Then drop one character from the left, and slide forward. The max frequency never needs to go down, because the answer only grows when it grows.
Changes needed equal window length minus the top count. The window slides, and never shrinks by more than one.
Run the animation above on your own input, or watch the 1:41 video explanation of Longest Repeating Character Replacement with a dry run and Java code.