Longest Repeating Character Replacement
Explanation & Solution
Description
Given a string s and an integer k, you can choose any character of the string and change it to any other uppercase English letter. You can perform this operation at most k times.
Return the length of the longest substring containing the same letter you can get after performing the above operations.
Input: s = "ABAB", k = 2
Output: 4
Explanation: Replace the two A's with B's (or the two B's with A's) to get a substring of 4 identical characters.
Constraints
1 <= s.length <= 10⁵sconsists of only uppercase English letters.0 <= k <= s.length
Approach
Sliding Window pattern
1. Initialize Variables
- Create a
countobject to track the frequency of each character in the current window. - Set
leftpointer to 0,maxFreqto 0 (tracks the highest frequency of any single character in the window), andmaxLento 0.
2. Expand the Window
- Iterate
rightfrom 0 tos.length - 1. - Add
s[right]to the frequency map and updatemaxFreqif this character now has the highest frequency.
3. Check the Window Validity
- The number of characters that need to be replaced is
windowSize - maxFreq, i.e.,(right - left + 1) - maxFreq. - If this exceeds
k, the window is invalid — we need more thankreplacements to make all characters the same.
4. Shrink the Window
- While the window is invalid, decrement the count of
s[left]and moveleftforward. - This shrinks the window until the number of replacements needed is at most
k.
5. Update the Maximum Length
- After ensuring the window is valid, update
maxLenwith the current window sizeright - left + 1.
6. Return the Result
- After processing all characters, return
maxLen— the length of the longest valid substring.
Key Insight
The key observation is that we don't need to track *which* character to replace — we just need to know the most frequent character in the window. The remaining characters (windowSize - maxFreq) are the ones we'd replace. If that count exceeds k, we shrink the window. Notably, maxFreq doesn't need to be perfectly accurate when shrinking — it only needs to be accurate when it leads to a new maximum window, which it always is.
Visualization
Press ▶ or use ← → to step through