Solving tips
- Key validity test: a window is fixable when window_len - count_of_most_frequent_letter <= k, so you only replace the non-majority characters.
- Since validity is monotone, use a variable-size window: grow right unconditionally, shrink left while invalid, and record the max size.
- Optimization: track a stale max_freq that never decreases and slide (if not while), giving true O(n) instead of O(26*n) and never shrinking the window.
- Common pitfall: the formula is window_len - max_freq <= k (not max_freq <= k), and record best only when the window is valid.
Problem
You are given a string s of uppercase English letters and an integer k. You may change at most k characters of s to any other uppercase letters. Return the length of the longest substring consisting of a single repeated letter that you can produce this way.
Equivalently: find the longest window of s that can be made uniform by rewriting at most k of its characters.
Examples
s = "ABAB",k = 2β4β change bothAs (or bothBs) and the whole string becomes one letter.s = "AABABBA",k = 1β4β change the middleBin"AABA"to get"AAAA"(window indices 0β3;"ABBA" β "BBBB"also works).s = "AAAA",k = 0β4β already uniform; zero replacements needed.
Constraints
1 <= len(s) <= 10^5scontains only uppercase English letters (AβZ, so at most 26 distinct).0 <= k <= len(s)
Checking all O(nΒ²) windows is too slow at n = 10^5; the expected solution is O(n) (or O(26Β·n)).
Think about it first
Hint 1
For a fixed window, which characters should you replace? Everything except the most frequent letter. The window is fixable iffwindow_length - count_of_most_frequent_letter <= k.
Hint 2
As the window grows rightward it can only get harder to fix, and shrinking from the left can only help. That monotonicity means two pointers that never move backward suffice.Hint 3
Keep letter counts in the window. Extendright each step; while (right - left + 1) - max(counts) > k, decrement counts at s[left] and advance left. The answer is the largest valid window seen. (Bonus: you never need to shrink below the best size β a stale max frequency still yields the right answer.)