Problem overview
The function characterReplacement receives a string s of uppercase letters and an integer k. You may change any character of s into any other uppercase letter, at most k times in total. The function returns the length of the longest substring made of one repeated letter that you can get this way.
For s = "ABAB" and k = 2, changing both As gives "BBBB", so the answer is 4. For s = "AABABBA" and k = 1, changing the A at index 3 gives "AABBBBA", which holds "BBBB", and no single change gives a run of 5, so the answer is 4. For s = "ABBBAABBBBA" and k = 2, the answer is 9.
The budget is O(n) time and constant extra space: one count for each of the 26 letters.
Approach: a window that needs at most k changes
Fix a substring. The cheapest way to turn it into one repeated letter is to keep its most common letter and change all the others. So a substring of length len whose most common letter appears maxCount times needs len - maxCount changes. It is a valid answer when len - maxCount <= k.
Trying every substring and counting its letters is far too slow for 100,000 characters. A sliding window does it in one pass. The window runs from index first to index last and only moves right:
- Move
lastright by one, adding that letter to the window's counts. - While the window needs more than
kchanges, drop its first letter and movefirstright. - The window is now valid. Keep its length if it is the longest so far.
Both ends only move right, so each moves at most n times and the whole run is O(n).
There is one subtle shortcut. Keeping the exact largest count in the window would mean scanning the 26 counts after every removal. The lesson never lowers maxCount when a letter leaves. The value can then be larger than the real maximum, but this can't produce a wrong answer. A window only matters if it is longer than the best found so far. For a longer window to count, some letter must reach a count above the stale maxCount, and that raises maxCount to a true value. A stale value can only make the window stay at its current length instead of shrinking, never grow past a valid length.
The trace for s = "AABABBA" and k = 1:
last char first window maxCount answer
0 A 0 A 1 1
1 A 0 AA 2 2
2 B 0 AAB 2 3
3 A 0 AABA 3 4
4 B 1 ABAB 3 4
5 B 2 BABB 3 4
6 A 3 ABBA 3 4
At last = 3, the window "AABA" holds three As and needs one change, so it is valid, with length 4. At last = 4 the next B makes the window "AABAB", which needs 5 - 3 = 2 changes, so first moves right once. The remaining window "ABAB" shows the stale count at work: it really needs two changes, but maxCount is still 3, so the window is kept at length 4 and the answer doesn't grow. The result is 4, as expected.
Step by step
- Create
count, avector<int>of 26 zeros:count[0]counts theAs in the window,count[1]theBs, and so on. - Declare
maxCountas 0. It tracks the largest count of one letter in the window. - Declare
answerandfirstas 0: the longest valid window so far and the window's left end. - Loop
lastfrom 0 up tos.size(). Each turn adds the letter atlastto the window. - Compute
indexass[last] - 'A', which is 0 forA, 1 forBand so on, because acharis a number in C++ and the uppercase letters are consecutive. Add 1 tocount[index]. - Update
maxCountwithmax(maxCount, count[index]). Only the letter just added changed its count, so only it can beat the old maximum. - Shrink while the window is invalid.
last - first + 1 - maxCount > kreads as: window length, minus the letters kept, is more than the allowed changes. - Drop the first letter inside that loop: decrease
count[s[first] - 'A']and increasefirst. LeavemaxCountalone, for the reason above. - Update
answerwithmax(answer, last - first + 1). After the shrinking, the window counts as one that needs at mostkchanges. - Return
answer.
The solution in C++
class Solution {
public:
int characterReplacement(string s, int k) {
vector<int> count(26, 0);
int maxCount = 0;
int answer = 0, first = 0;
for (int last = 0; last < s.size(); last++) {
int index = s[last] - 'A';
count[index]++;
maxCount = max(maxCount, count[index]);
while (last - first + 1 - maxCount > k) {
count[s[first] - 'A']--;
first++;
}
answer = max(answer, last - first + 1);
}
return answer;
}
};
The C++ details worth a closer look:
chararithmetic.s[last] - 'A'subtracts twochars, and the result is anint. For uppercase letters it is in the range 0 to 25, a valid index forcount. A lowercase letter would give a number from 32 up and write outside the vector, which is undefined behaviour. The constraints promise uppercase only.vector<int> count(26, 0). The first argument is the size and the second the value of every element. Plainvector<int> count(26)would also give zeros.maxwith twoints.max(a, b)from<algorithm>needs both arguments of the same type.count[index]andmaxCountare bothint.- Signed and unsigned.
s.size()is unsigned, andlast < s.size()compares anintwith it. That is safe here becauselastis never negative, though some compilers warn. Don't writes.size() - 1in a loop condition: for an empty string it wraps to a huge number. - The string is copied.
sis taken by value. That costsO(n)once per call and doesn't change the complexity.
Complexity
Time: O(n). last visits each index once. first only moves right and never passes last, so the while body runs at most n times in total across the whole run, not per turn of the for. Each step is constant work.
Space: O(1). The count vector always holds 26 integers, whatever 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 already ins."AAAB"withk = 0gives 3, and"ABAB"withk = 0gives 1.kas large as the string. Every character can be changed, so the answer iss.size():"ABC"withk = 3gives 3.- A single character.
"A"withk = 0gives 1. - One letter only. A string of 100,000
Zs withk = 0gives 100000: the window never shrinks. - Counting changes as the number of letters different from the first. The cheapest plan keeps the most common letter of the window, which may not be the first or the last one.
- Recomputing the maximum on every step. It is correct, but it adds a scan of 26 counts to every step, which the stale
maxCountmakes unnecessary. - Forgetting to decrease
countwhen a letter leaves. The counts would describe more than the window, andmaxCountwould be inflated.
Testing
s = "ABAB",k = 2gives4.s = "AABABBA",k = 1gives4.s = "ABBBAABBBBA",k = 2gives9.s = "AAAB",k = 0gives3.s = "ABAB",k = 0gives1.s = "ABC",k = 3gives3.s = "A",k = 0gives1.
