Problem overview
The method characterReplacement receives a string s of uppercase letters and an integer k. You may change any character into any other uppercase letter, at most k times in total. The method returns the length of the longest substring made of a single repeated letter that you can get this way. A substring is a run of consecutive characters.
For s = "AABABBA" and k = 1 the answer is 4. Changing the A at index 3 gives "AABBBBA", which holds "BBBB". Changing the B at index 2 gives "AAAA" instead. No single change reaches 5. For s = "ABBBAABBBBA" and k = 2 the answer is 9: changing the two As at indexes 4 and 5 turns indexes 1 to 9 into Bs.
Approach: a window that needs at most k changes
Look at one window, a substring from index first to index last. The cheapest way to make it one letter is to keep its most common letter and change every other one. So the number of changes needed is the window's length minus the count of its most common letter. The window is good when that number is at most k, and the answer is the length of the longest good window.
That suggests a sliding window. Move last to the right one character at a time, which adds a letter to the window. If the window now needs more than k changes, move first to the right until it needs at most k again. Both ends only move right, so each index enters and leaves the window at most once, and the whole scan is O(n). Checking every substring would take O(n²) windows, which is too slow for 100,000 characters.
The counts live in a list of 26 integers, one per letter, so the extra space is O(1).
Here is the scan on "AABABBA" with k = 1:
last=0 A window "A" maxCount=1 answer=1
last=1 A window "AA" maxCount=2 answer=2
last=2 B window "AAB" maxCount=2 answer=3
last=3 A window "AABA" maxCount=3 answer=4
last=4 B window "ABAB" maxCount=3 answer=4
last=5 B window "BABB" maxCount=3 answer=4
last=6 A window "ABBA" maxCount=3 answer=4
At last=4 the window "AABAB" would need 5 - 3 = 2 changes, more than k, so first moves one step right and the window becomes "ABAB".
Step by step
- Create
countas[0] * 26. Slot 0 counts theAs in the window, slot 1 theBs, and so on. - Create
maxCountat 0. It holds the largest count of one letter seen in the window. - Set
answer = first = 0.firstis the window's left end, andansweris the longest good window so far. - Loop
lastoverrange(len(s)). Each turn adds the letter atlastto the window. - Convert the letter to a slot number with
ord(s[last]) - ord('A'), then add 1 to that count. Letters have consecutive codes, soAmaps to 0 andZto 25. - Update
maxCountwithmax. Only the letter just added changed its count, so it is the only one that can set a new maximum. - Shrink while the window is too costly. The window's length is
last - first + 1. SubtractmaxCountto get the number of changes, and loop while that exceedsk. - Drop the first letter: subtract 1 from its count and add 1 to
first. - Record the window's length in
answerwithmax. At this point the window needs at mostkchanges. - Return
answer.
The solution in Python
class Solution:
def characterReplacement(self, s: str, k: int) -> int:
count = [0] * 26
maxCount = 0
answer = first = 0
for last in range(len(s)):
index = ord(s[last]) - ord('A')
count[index] += 1
maxCount = max(maxCount, count[index])
while last - first + 1 - maxCount > k:
count[ord(s[first]) - ord('A')] -= 1
first += 1
answer = max(answer, last - first + 1)
return answer
Details worth a closer look:
- Chained assignment.
answer = first = 0gives both names the integer 0. Integers are immutable, so later changes to one name never affect the other. The same line with a list would make both names refer to one shared list, which is whycountis created on its own line. [0] * 26builds a list of 26 zeros. This is safe for integers, because adding 1 tocount[index]replaces that slot with a new integer.ordturns a one-character string into its code.ord('B') - ord('A')is 1. Indexing a string, as ins[last], gives a one-character string.- Why
maxCountis never lowered. When a letter leaves the window,maxCountcan be larger than the true maximum. In the trace, after"AABAB"shrinks to"ABAB", the true maximum is 2 whilemaxCountstays 3. That is harmless: a stale value can only stop the window from shrinking, so the window keeps the length of the best one found so far, andanswerdoesn't grow. To beat the current answer, a later window needs a letter whose count exceeds the stale value, and thenmaxCountrises for real.
Complexity
Time: O(n). The for loop runs n times. The while loop moves first to the right and first never moves back, so across the whole run its body executes at most n times in total. Everything else is constant work.
Space: O(1). The list always has 26 slots, whatever the length of s.
Edge cases and common mistakes
- No changes allowed. With
k = 0the answer is the longest run of one repeated letter:"AAAA"gives 4 and"ABC"gives 1. kas large as the string."ABC"withk = 3gives 3, the whole string.- A single character.
"A"withk = 0gives 1. - Counting changes the wrong way. The cost is the window length minus the largest count, not minus the count of the letter at
last. - Off-by-one window length. The length of the window from
firsttolastinclusive islast - first + 1. - Recounting the window. Scanning the 26 counts or the window for its maximum on every step also works, but it is wasted effort here. The running
maxCountis enough for the answer. - Forgetting to decrement. If the dropped letter's count is not reduced, the counts no longer describe the window and the answer comes out too large.
Testing
s = "ABAB",k = 2gives4.s = "AABABBA",k = 1gives4.s = "ABBBAABBBBA",k = 2gives9.s = "ABCDE",k = 1gives2.s = "ABC",k = 0gives1.s = "ABC",k = 3gives3.
