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 into any other uppercase letters. The method returns the length of the longest substring that consists of a single repeated letter after those changes.
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 produces a run of 5. For "ABAB" with k = 2 the whole string can become one letter, so the answer is 4.
The target is 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
Instead of thinking about which characters to change, think about which substrings could become a single letter. A substring can become one repeated letter if the number of characters that differ from its most common letter is at most k. The best plan for any substring is to keep its most common letter and change all the others, so its cost is length - (count of the most common letter).
That turns the task into: find the longest window whose length minus its largest letter count is at most k. A sliding window does this in one pass. The right end last moves forward one character at a time. When the window becomes too expensive, the left end first moves forward until it is acceptable again. Both ends only move right, so each character enters and leaves at most once.
Trying every substring and counting its letters would take O(n²) or worse. The window reuses its counts, adding the new letter and removing the old one, so each move costs O(1).
One detail is the largest count, maxCount. When a letter leaves the window, the code doesn't lower maxCount, even though it may now be larger than the real maximum. This is safe. The answer only grows when the window finds a longer valid length, which needs a letter whose count exceeds the old maxCount, and that raises maxCount for real. A stale value can only keep the window from shrinking below the best length already found, and that length is already recorded in answer.
Here is the run on "AABABBA" with k = 1, printing the window start, maxCount and answer after each step of last:
last=0 first=0 maxCount=1 answer=1
last=1 first=0 maxCount=2 answer=2
last=2 first=0 maxCount=2 answer=3
last=3 first=0 maxCount=3 answer=4
last=4 first=1 maxCount=3 answer=4
last=5 first=2 maxCount=3 answer=4
last=6 first=3 maxCount=3 answer=4
At last = 4 the window "AABAB" has length 5 and maxCount = 3, so it needs 2 changes. That is more than k = 1, so first moves to 1. From then on the window keeps length 4, and the answer stays 4.
Step by step
- Create
count, anint[]of size 26.count[0]counts the A's in the window,count[1]the B's, and so on. C# fills a newintarray with zeros. - Declare
maxCountas 0. It holds the largest count of one letter seen in the window. - Declare
answerandfirst, both 0.firstis the left end of the window andansweris the longest good window so far. - Loop
lastfrom 0 tos.Length - 1. Each turn adds the letter atlastto the window. - Convert the letter to an index with
s[last] - 'A', then add 1 tocount[index]. - Update
maxCountwithMath.Max. 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 too expensive. The length is
last - first + 1, and subtractingmaxCountleaves the characters that would have to change. The loop runs while that is greater thank. - Drop the first letter inside the loop: decrease its count and move
firstright.maxCountstays as it is. - Record the length with
answer = Math.Max(answer, last - first + 1). At this point the window needs at mostkchanges. - Return
answerafter the loop.
The solution in C#
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[last] - 'A';
count[index]++;
maxCount = Math.Max(maxCount, count[index]);
while (last - first + 1 - maxCount > k) {
count[s[first] - 'A']--;
first++;
}
answer = Math.Max(answer, last - first + 1);
}
return answer;
}
}
The C# details worth knowing:
- Subtracting chars gives an
int.s[last]is achar, and'A'is achar. The-operator converts both toint, so'C' - 'A'is 2. Because A to Z are consecutive, this maps each letter to 0 through 25. s.Length, nots.Length(). On astring,Lengthis a property, so it has no parentheses. Code ported from Java or Python often gets this wrong.s[i]is read-only. Strings are immutable in C#, which is fine here: the method never changess, it only counts letters.count[index]++works on array elements. It increments the element in place, andcount[s[first] - 'A']--decrements one the same way.- Several declarations on one line.
int answer = 0, first = 0;declares twointvariables, each with its own initial value.
Complexity
Time: O(n). The for loop runs n times. The inner while loop moves first to the right and never moves it back, so across the whole run its body executes at most n times in total. Everything else in the loop is constant work.
Space: O(1). The count array has 26 entries whatever the length of the string. A string of 100,000 letters uses the same memory for counting as a string of 3.
Edge cases and common mistakes
- A single character.
"A"withk = 0returns 1. - One repeated letter.
"AAAA"withk = 0returns 4, and a string of 100,000 A's withk = 0returns 100000. k = 0. The answer is the longest run that already exists."ABCD"gives 1,"AAAB"gives 3, and"ABAA"gives 2.kas large as the string."ABCD"withk = 4returns 4, because every character may change. Withk = 1the same string returns 2.- Counting the number to change wrongly. The cost is the window length minus the largest count, not the number of distinct letters.
- Moving
firstbackwards or resetting it. The window only ever slides to the right. Restarting the left end from 0 after a failure turns the pass intoO(n²). - Forgetting
- 'A'.count[s[last]]would use the character code (65 to 90) as an index, which is outside an array of 26 elements and throwsIndexOutOfRangeException. - Recomputing
maxCountby scanning all 26 counts after every removal is correct but slower by a constant factor. The lazy version is enough.
Testing
"ABAB",k = 2gives4."AABABBA",k = 1gives4."ABBBAABBBBA",k = 2gives9."A",k = 0gives1."ABCD",k = 0gives1."ABCD",k = 1gives2."ABCD",k = 4gives4."AAAB",k = 0gives3.
