Problem overview
The method characterReplacement receives a string s of uppercase letters and an integer k. You may change at most k characters of s, each into any uppercase letter. The method 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 gives "AABBBBA", which contains "BBBB". Changing the B at index 2 gives "AAAA" instead. No single change gives a run of 5.
Approach
Instead of trying every change, look at windows: substrings from index first to index last. A window can become one repeated letter if the number of characters that are not its most common letter is at most k. The best plan for a window is to keep its most common letter and change all the others, so the condition is:
window length - count of the most common letter <= k
Checking every window with its own count would cost O(n²) or worse. A sliding window does it in one pass: the right end last moves forward one letter at a time, and whenever the window needs more than k changes, the left end first moves forward until it is valid again. Both ends only move right, so the work is O(n). Because the letters are only A to Z, the counts fit in an array of 26 numbers, which is O(1) space.
Step by step
- Count the letters in the window.
counthas 26 zeros:count[0]is the number of A's in the window,count[1]the number of B's, and so on. - Remember the largest count.
maxCountstarts at 0 and holds the highest count of one letter seen in the window. - Set up the window and the answer.
firstis the window's left end andanswerthe longest valid window found so far. Both start at 0. - Grow the window. A
forloop moveslastover every index ofs, adding one letter per turn. - Turn the letter into an index.
s.charCodeAt(last)is the character's code. The codes of A to Z are consecutive, so subtracting the code of'A'gives 0 for A, 1 for B and so on. Add one to that count. - Update
maxCount. Only the letter just added changed, so it is the only one that can beat the old maximum:Math.max(maxCount, count[index]). - Shrink while the window needs too many changes.
last - first + 1is the window's length. SubtractmaxCount, the letters kept, and what is left is the number of letters to change. While that is more thank, the window is invalid. - Drop the first letter. Inside the
while, lower the count of the letter atfirstand movefirstright by one. - Record the length. Once the window needs at most
kchanges, all of it can become one letter, soanswerbecomes the larger of itself andlast - first + 1. - Return
answer.
The solution in TypeScript
class Solution {
characterReplacement(s: string, k: number): number {
let count: number[] = 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;
}
}
Details worth knowing:
- Characters have no numeric value of their own. A string's character is another string, so subtracting
'A'from it does not give a letter number. UsecharCodeAt:"B".charCodeAt(0) - "A".charCodeAt(0)is 1. Using it on"Z"gives 25, the last slot ofcount. new Array(26).fill(0)creates 26 slots and fills each with0. Withoutfill, the slots would be empty andcount[index]++would produceNaN.- Counts are plain numbers. They are doubles, but with strings of at most 100,000 characters every count stays far below the size where whole numbers stop being exact.
Why maxCount is never lowered
When a letter leaves the window, maxCount is not recomputed, so it can be larger than the real maximum of the current window. This does no harm. The window only fails to shrink in those moments, so its length never drops below the best length found so far, and answer only grows. A longer valid window needs a letter whose count really is bigger, and that raises maxCount for real. Recomputing the maximum from the 26 counts each time would also work, but costs more for no gain.
Walking through an example
For s = "AABABBA" and k = 1, each turn of the loop ends with this window:
last | letter | window | maxCount | answer |
|---|---|---|---|---|
| 0 | A | "A" | 1 | 1 |
| 1 | A | "AA" | 2 | 2 |
| 2 | B | "AAB" | 2 | 3 |
| 3 | A | "AABA" | 3 | 4 |
| 4 | B | "ABAB" | 3 | 4 |
| 5 | B | "BABB" | 3 | 4 |
| 6 | A | "ABBA" | 3 | 4 |
At last = 4 the window "AABAB" has length 5 and a largest count of 3, so it needs 2 changes. That is more than k = 1, so first moves once. From then on the window keeps its length of 4 while sliding right.
Complexity
Time: O(n). last visits each index once, and first only moves right, so the while body runs at most n times over the whole call. Space: O(1). The array has 26 slots no matter how long s is.
Edge cases and common mistakes
k = 0. No change is allowed, so the answer is the longest run of one letter already ins:"ABAB"withk = 0gives 1, and"AAAA"gives 4.kat least the length ofs. Everything can be changed, so the window never shrinks and the answer iss.length:"ABCDE"withk = 5gives 5.- A single letter.
"A"withk = 0gives 1. - Forgetting the
+ 1in the length. A window fromfirsttolastinclusive haslast - first + 1letters. - Checking the wrong letter. The best letter to keep is the most common one in the window, not the letter at the right end.
Testing
s | k | Result |
|---|---|---|
"ABAB" | 2 | 4 |
"AABABBA" | 1 | 4 |
"ABBBAABBBBA" | 2 | 9 |
"A" | 0 | 1 |
"ABCDE" | 0 | 1 |
"ABCDE" | 5 | 5 |
"AAAA" | 0 | 4 |
"ABAB" | 0 | 1 |
