Longest Repeating Character Replacement
Find the longest run of one letter you can make by changing at most k letters, with a sliding window.
The problem
You get a string s of uppercase English letters and an integer k. You may change any letter into any other uppercase letter, at most k times in total. Return the length of the longest substring that can be made of one repeated letter after those changes.
Input s = "BAAACAB", k = 1
Output 5
Change the C in "AAACA" to get five A's in a row.
Input s = "AABBBA", k = 0
Output 3
With no changes allowed, the answer is the longest run already there, BBB.
How to spot the pattern
- You want the longest window that can be fixed with a limited budget of k changes.
- A window is fixable when its length minus the count of its most frequent letter is at most k.
The idea
A window can become one repeated letter when length - maxCount <= k, where maxCount is the count of its most frequent letter: the other letters are the ones you would change. Grow the window on the right, and when it needs more than k changes, slide its left edge forward by one so the length stays the same. You never have to lower maxCount, because a longer valid window can only appear once some letter's count beats the old maxCount.
Brute force: For every substring, keep letter counts and check whether its length minus the top count is at most k, which takes O(n^2) time.
Step by step
- 1Keep a count for each of the 26 letters, with
left = 0,maxCount = 0andbest = 0. - 2For each
right, add 1 to the count ofs[right]and updatemaxCountwith it. - 3If
(right - left + 1) - maxCount > k, subtract 1 from the count ofs[left]and moveleftone step right. - 4Update
bestwith the window lengthright - left + 1, and return it at the end.
See the pattern move
The sliding window pattern on a small example. Step through it, or press play.
Code
class Solution:
def characterReplacement(self, s: str, k: int) -> int:
counts = [0] * 26 # letter counts inside the window
left = 0
max_count = 0 # highest count of one letter seen in a window so far
best = 0
for right in range(len(s)):
letter = ord(s[right]) - ord("A")
counts[letter] += 1
max_count = max(max_count, counts[letter])
if (right - left + 1) - max_count > k:
# too many changes needed: slide the window one step
counts[ord(s[left]) - ord("A")] -= 1
left += 1
best = max(best, right - left + 1)
return bestComplexity
Time
O(n)
Space
O(1)
Each step does constant work with 26 counters, and left and right each move at most n times.
Watch out for
- Counting the changes as the number of distinct letters minus 1; what matters is the window length minus the count of its most frequent letter.
- Forgetting to lower the count of
s[left]when the window slides, so the counts drift away from the real window. - Throwing the window away and starting over when it becomes invalid, which loses the O(n) bound.
Follow-up questions
Why is it fine that maxCount never goes down?
The answer can only beat best when some letter's count beats the old maxCount. Until that happens the window just slides at its current length, so a stale maxCount never adds a wrong answer. Recomputing the true maximum over 26 letters at each step also works, at O(26 n).
What if the string can hold any characters?
Swap the 26 counters for a hash map from character to count. The window logic stays exactly the same.
In Hinglish
Window ki length minus sabse zyada aane wale letter ki ginti, utne changes chahiye; yeh k se zyada ho jaaye toh left ko ek step aage karo.