Problem overview
The function characterReplacement receives a string s of uppercase letters and an integer k. You may change at most k characters, each into any uppercase letter. The function returns the length of the longest substring made of one 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 into a B gives "AABBBBA", which contains "BBBB". No single change makes a run of 5. For s = "ABBBAABBBBA" and k = 2 the answer is 9: change the two As at indexes 4 and 5, and indexes 1 to 9 all become B.
The target is O(n) time and O(1) extra space, where the space is one counter for each of the 26 letters.
Approach: a window that needs at most k changes
Think of a window, the substring from index first to index last. If you want the whole window to become one letter, the cheapest plan is to keep its most common letter and change every other one. The number of changes is therefore:
window length - count of the most common letter
A window is good when that number is at most k. The answer is the length of the longest good window.
Trying every substring and counting its letters would be far too slow for 100,000 characters. The sliding window avoids that. The right end last moves one step at a time and adds a letter. If the window now needs more than k changes, the left end first moves right until it is good again. Both ends only move forward, so each moves at most n times and the total work is O(n).
Step by step
- Make 26 counters.
make([]int, 26)creates a slice of zeros. Position 0 counts theAs in the window, position 1 theBs, and so on. - Track
maxCount, the largest count of one letter in the window, starting at 0. - Start with an empty window.
answeris the best length so far andfirstis the left end; both are 0. - Grow to the right. A
forloop moveslastfrom 0 tolen(s) - 1, and every turn adds the letter atlast. - Count the new letter.
s[last]is a byte holding the letter's code. The codes of A to Z are consecutive, so subtracting'A'turns a letter into a number from 0 to 25, which indexescount. - Update
maxCount. Only the letter just added changed its count, so it is the only one that can beat the old maximum. - Shrink while the window is bad. The window length is
last-first+1. SubtractmaxCountand what is left is the number of letters to change. While that exceedsk, the inner loop runs. Go has nowhile, so this is aforwith only a condition. - Drop the first letter. Decrease its counter and move
firstright. - Record the length. Now the window needs at most
kchanges, soanswerbecomes the larger of itself and the window length. - Return
answer.
The solution in Go
func characterReplacement(s string, k int) int {
count := make([]int, 26)
maxCount := 0
answer, first := 0, 0
for last := 0; last < len(s); last++ {
index := s[last] - 'A'
count[index]++
maxCount = max(maxCount, count[index])
for last-first+1-maxCount > k {
count[s[first]-'A']--
first++
}
answer = max(answer, last-first+1)
}
return answer
}
Here is the run on s = "AABABBA" with k = 1:
last=0 letter=A first=0 window=A maxCount=1 answer=1
last=1 letter=A first=0 window=AA maxCount=2 answer=2
last=2 letter=B first=0 window=AAB maxCount=2 answer=3
last=3 letter=A first=0 window=AABA maxCount=3 answer=4
last=4 letter=B first=1 window=ABAB maxCount=3 answer=4
last=5 letter=B first=2 window=BABB maxCount=3 answer=4
last=6 letter=A first=3 window=ABBA maxCount=3 answer=4
Each row shows the window after the shrinking step. The window grows to length 4 at last=3. After that it slides along at length 4, because every longer window would need two changes.
Why maxCount is never lowered
When a letter leaves the window, the code decreases its counter but leaves maxCount alone, so maxCount can be larger than the real maximum. At last=4 above, the window "ABAB" has a real maximum of 2, yet maxCount is still 3. That is safe. A stale value can only make the window look better than it is, and the only effect is that the window slides along at its current length instead of shrinking. The answer can grow only when the window gets longer, and a longer good window needs a letter whose count really exceeds the old maximum. That raises maxCount for real. So answer never takes a length that is not achievable.
Go details
s[last]is a byte. Indexing a string gives abyte(uint8), not a character.s[last] - 'A'is therefore abytetoo, from 0 to 25 for uppercase letters. Go accepts it as a slice index, because any integer type can index a slice.:=and the multiple assignment.answer, first := 0, 0declares both variables at once, asints.max. Since Go 1.21,maxis built in and works on any two ordered values of the same type. There is nothing to import.foris the only loop. The outerforhas the three parts (start, condition, step), and the inner one has only a condition, which is how Go writes awhileloop.len(s)counts bytes. That equals the number of letters here, because the input contains only A to Z.
Complexity
Time: O(n). last visits each index once. first only moves right and never passes last, so the inner loop's body runs at most n times in total across the whole run.
Space: O(1). The slice has 26 integers whatever the length of the string, plus a few integer variables.
Edge cases and common mistakes
k = 0. No changes are allowed, so the answer is the longest run of one letter that is already there."BAAAB"gives 3, and"ABC"gives 1.kequals the length. Every character can be changed, so"ABC"withk = 3gives 3.- One character.
"A"withk = 0gives 1. - A string that is already one letter.
"AAAA"withk = 0gives 4, and the inner loop never runs. - Recomputing the maximum over 26 counters every turn. It is still linear, but it is unnecessary, because only the new letter can raise it.
- Forgetting to subtract
'A'. A letter's raw code is 65 to 90, which is outside a slice of 26 elements and panics with an index out of range error. - Measuring the window as
last-first. The length of a window that includes both ends islast-first+1.
Testing
s = "ABAB",k = 2gives4.s = "AABABBA",k = 1gives4.s = "ABBBAABBBBA",k = 2gives9.s = "BAAAB",k = 0gives3.s = "ABC",k = 0gives1.s = "ABC",k = 3gives3.
