Problem overview
The method characterReplacement receives a string s of uppercase letters and an integer k. You may change up to k characters of s into any other uppercase letters. It returns the length of the longest substring that can be made of a single repeated letter this way.
For s = "AABABBA" and k = 1, changing the A at index 3 into a B gives AABBBBA, which contains BBBB, so the answer is 4. For s = "ABBBAABBBBA" and k = 2, changing the two As at indexes 4 and 5 turns indexes 1 to 9 into nine Bs, so the answer is 9.
Approach: a window that needs at most k changes
Look at one substring. To turn it into a single repeated letter with as few changes as possible, keep its most common letter and change every other letter. The cost is therefore:
window length - count of the most common letter in it
A substring is a valid answer exactly when that cost is at most k. So the task becomes: find the longest window whose length minus its largest letter count is at most k.
That suits a sliding window. The right end last moves forward one letter at a time and adds that letter to the window. When the window has become too expensive, the left end first moves forward to shrink it. Both ends only move right, so the work is O(n). Trying every substring and counting its letters would be O(n squared) or worse.
A table of 26 counts, one per letter, describes the window's contents. It has a fixed size, so the extra space is O(1).
Step by step
- Create
count, anint[26]. Index 0 counts theAs in the window, index 1 theBs, and so on. Java fills a newintarray with zeros. - Declare
maxCount, the largest count of one letter in the window, starting at 0. - Declare
answerandfirstas 0.firstis the window's left end andansweris the longest valid window so far. - Loop
lastfrom 0 tos.length() - 1. Each turn adds the letter atlastto the window. - Find the letter's slot.
s.charAt(last) - 'A'is 0 forA, 1 forBand so on. Acharis a number in Java and the letters are consecutive, so the subtraction gives anint. Then add 1 tocount[index]. - Update
maxCountwithMath.max. 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 expensive:
last - first + 1 - maxCount > k. The first part is the window length, so the whole expression is the number of letters you would have to change. - Drop the leftmost letter by decreasing its count and moving
firstright by one. - Record the length. After the shrinking, the window needs at most
kchanges, soanswerbecomes the larger of itself andlast - first + 1. - Return
answer.
The solution in Java
class Solution {
public int characterReplacement(String s, int k) {
int[] count = new int[26];
int maxCount = 0;
int answer = 0, first = 0;
for (int last = 0; last < s.length(); last++) {
int index = s.charAt(last) - 'A';
count[index]++;
maxCount = Math.max(maxCount, count[index]);
while (last - first + 1 - maxCount > k) {
count[s.charAt(first) - 'A']--;
first++;
}
answer = Math.max(answer, last - first + 1);
}
return answer;
}
}
Details worth understanding:
- Why
maxCountis never lowered. When a letter leaves the window,maxCountmay be larger than the real maximum. That stale value can make the window look cheaper than it is, so the window may stay at a size that is not valid. That is harmless: such a window is no longer than the best one already recorded inanswer, so it cannot raise the answer. A longer window can only count as valid after some letter reaches a count above the stalemaxCount, and thenmaxCountis raised for real. Keeping the old value saves a scan of the 26 counts at every step. chararithmetic. Ins.charAt(last) - 'A'both operands are promoted toint, so the result is anintthat can index an array directly. This only works because the input contains uppercase letters; any other character would give an index outside0to25and throwArrayIndexOutOfBoundsException.s.length()is a method onString, while.lengthwithout parentheses is the field of an array.
Complexity
Time: O(n). last visits each index once, and first only moves right, so the while loop's body runs at most n times over the whole call.
Space: O(1). The 26-slot array and a few integers don't depend on the length of s.
Edge cases and common mistakes
k = 0. No changes are allowed, so the answer is the longest run of one letter."AAAA"gives 4,"ABCD"gives 1 and"AABA"gives 2.kas large as the string. Every letter can be changed, so the answer is the whole length:"ABCD"withk = 4gives 4.- A single letter.
"A"withk = 0gives 1. - Counting the cost as
maxCountalone. The test islength - maxCountagainstk, notmaxCountagainstk. - Off-by-one in the length. A window from
firsttolast, both included, holdslast - first + 1letters. - Forgetting to decrease the count of the letter that leaves. The counts then describe letters that are no longer in the window.
Testing
"ABAB",k = 2gives 4."AABABBA",k = 1gives 4."ABBBAABBBBA",k = 2gives 9."AAAA",k = 0gives 4."ABCD",k = 0gives 1."ABCD",k = 4gives 4.
