Problem overview
characterReplacement(s, k) 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.
For s = "AABABBA" and k = 1 the answer is 4. Changing the A at index 3 into a B turns the middle into "BBBB". No single change produces a run of 5.
The statement asks for O(n) time and O(1) extra space: one counter for each of the 26 letters.
Approach: a window that needs at most k changes
Trying every substring and counting its letters would take O(n²) or worse. A sliding window does it in one pass. The window is the substring from index first to index last, and a small array of counts describes the letters inside it.
The key question for a window is how many changes it needs. The best plan is to keep its most common letter and change every other character. So:
changes needed = window length - count of the most common letter
If that number is at most k, the whole window can become one letter, and its length is a candidate for the answer. If it is bigger than k, the window is too wide, so its left end moves right until it fits again.
The right end moves forward one character at a time, and the left end only moves right. Each index enters the window once and leaves at most once, which gives the linear time.
Here is the run on "AABABBA" with k = 1:
last | letter added | first after shrinking | maxCount | window length | answer |
|---|---|---|---|---|---|
| 0 | A | 0 | 1 | 1 | 1 |
| 1 | A | 0 | 2 | 2 | 2 |
| 2 | B | 0 | 2 | 3 | 3 |
| 3 | A | 0 | 3 | 4 | 4 |
| 4 | B | 1 | 3 | 4 | 4 |
| 5 | B | 2 | 3 | 4 | 4 |
| 6 | A | 3 | 3 | 4 | 4 |
Step by step
- Create the counters.
new Array(26).fill(0)makes 26 zeros:count[0]counts the A's in the window,count[1]the B's, and so on. - Track
maxCount, the largest count of one letter seen in the window. - Declare
answerandfirst, both starting at 0.firstis the window's left end. - Loop with
lastfrom 0 tos.length - 1. Each turn adds the letter atlastto the window. - Convert the letter to a number from 0 to 25.
charCodeAtgives the character's code, and the codes of A to Z are consecutive, so subtracting the code of'A'gives 0 for A, 1 for B and so on. Then increase that count. - Update
maxCount. Only the letter just added changed its count, so it is the only one that can beat the current maximum. - Shrink while the window needs too many changes:
last - first + 1 - maxCount > k. The first part is the window length. - Drop the first letter by decreasing its count and moving
firstright. - Update
answerwith the current window length. At this point the window needs at mostkchanges. - Return
answer.
The solution in JavaScript
class Solution {
characterReplacement(s, k) {
let count = new Array(26).fill(0);
let maxCount = 0;
let answer = 0, first = 0;
for (let last = 0; last < s.length; last++) {
let index = s.charCodeAt(last) - 'A'.charCodeAt(0);
count[index]++;
maxCount = Math.max(maxCount, count[index]);
while (last - first + 1 - maxCount > k) {
count[s.charCodeAt(first) - 'A'.charCodeAt(0)]--;
first++;
}
answer = Math.max(answer, last - first + 1);
}
return answer;
}
}
The details worth a closer look:
charCodeAtreturns a number."B".charCodeAt(0)is 66 and'A'.charCodeAt(0)is 65, so the difference is 1. Indexing a string likes[last]gives a one-character string, which can't be used as an array position for this purpose.new Array(26).fill(0).new Array(26)alone makes 26 empty slots.fill(0)sets each to0, socount[index]++starts from a number. Counting on anundefinedslot would giveNaN.- Several variables in one
let.let answer = 0, first = 0;declares both, each with its own initial value. Math.max. It returns the larger of its arguments, which keepsmaxCountandanswerfrom ever going down.
Why maxCount never goes down
When a letter leaves the window, the code lowers its count but not maxCount. That looks wrong, since maxCount may now be larger than the real largest count in the window. In the table above, at last = 4 the window is "ABAB" (indexes 1 to 4), whose real largest count is 2, while maxCount is still 3.
It still gives the right answer. The result can only grow when a window longer than the best one so far becomes valid, and that needs a letter whose real count exceeds the old maxCount. When that happens, maxCount is raised for real. In the meantime, a stale value only stops the window from shrinking below the best length already found. So the window never gets smaller once it has reached a given size; it slides along, and answer is the largest size it reached.
Complexity
Time: O(n). last visits each index once, and first only moves right, so the body of the while loop runs at most n times in total across the whole run. Each step is constant work.
Space: O(1). The count array has 26 entries whatever the length of s.
Edge cases and common mistakes
k = 0. No changes are allowed, so the answer is the longest existing run. For"AABABBA"it is 2, and for"ABCDE"it is 1.kas large as the string. Every character can be changed, so the answer iss.length. For"ABCDE"withk = 5the function returns 5.- One character.
"A"withk = 0gives 1. - Counting in the wrong direction. The cost is the window length minus the count of the most common letter, not the count itself.
- Off-by-one in the length. The window from
firsttolastinclusive haslast - first + 1characters. - Recomputing the maximum on every shrink. Scanning all 26 counts works too, but it isn't needed, as explained above.
- Using
ifinstead ofwhileto shrink. With a single step the window can stay invalid, because the one letter that left may not have been enough to bring the changes down tok.
Testing
s = "ABAB",k = 2gives4.s = "AABABBA",k = 1gives4.s = "ABBBAABBBBA",k = 2gives9.s = "ABAB",k = 1gives3.s = "AAAA",k = 0gives4.s = "AABABBA",k = 0gives2.s = "ABCDE",k = 0gives1.s = "ABCDE",k = 5gives5.
