Problem overview
characterReplacement receives a string s of uppercase letters and an integer k. You may change at most k characters of s into any uppercase letters. The function returns the length of the longest substring made of a single 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". For "ABAB" with k = 2 the whole string can become one letter, so the answer is 4. For "ABBBAABBBBA" with k = 2 the answer is 9.
The statement asks for O(n) time and O(1) extra space: one counter for each of the 26 letters.
Approach
Trying every substring and counting its letters would take at least O(n²) time. The faster idea looks at windows, meaning runs of consecutive characters between two indexes, first and last.
For a given window, the cheapest plan is to keep its most common letter and change every other letter. That costs window length - count of the most common letter changes. The window is usable when that number is at most k.
So the algorithm grows the window one character at a time on the right. When the window needs more than k changes, it shrinks from the left until it is valid again. The best answer is the largest length a valid window ever had. Each index enters the window once and leaves at most once, so the work is O(n).
The window does not have to be valid at every moment on its way to the answer. It only has to be valid when its length is recorded. In the run on "AABABBA" with k = 1 (shown below), the window reaches "AABA", which has three A's and one B: one change makes it all A's, so its length 4 is recorded. Adding the next B would make the window need two changes, so the left end moves right by one.
A window of length 5 would need a letter that appears 4 times, and no window of 5 has one, so the answer stays 4. The trace below shows how the counters get there.
Step by step
- Create
count, anIntArray(26)that starts with 26 zeros.count[0]counts the A's in the window,count[1]the B's, and so on. - Create
maxCount, starting at 0: the largest count of one letter seen in the window. - Create
answerandfirst, both starting at 0.firstis the left end of the window. - Loop
lastovers.indices. Each turn adds the letter atlastto the window. - Convert the new letter to an index. Subtracting two
Charvalues gives anInt, and the letters A to Z are consecutive, sos[last] - 'A'is 0 for A, 1 for B, and so on. Then add 1 to that counter. - Update
maxCount. 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 window has
last - first + 1letters. Take awaymaxCountand the rest are the letters to change. While that is more thank, the window is invalid. - Drop the first letter inside that loop: decrease its counter and move
firstright by one. - Record the length. After shrinking, the window is valid, so
answerbecomes the larger of itself andlast - first + 1. - Return
answer.
The solution in Kotlin
class Solution {
fun characterReplacement(s: String, k: Int): Int {
val count = IntArray(26)
var maxCount = 0
var answer = 0
var first = 0
for (last in s.indices) {
val index = s[last] - 'A'
count[index]++
maxCount = maxOf(maxCount, count[index])
while (last - first + 1 - maxCount > k) {
count[s[first] - 'A']--
first++
}
answer = maxOf(answer, last - first + 1)
}
return answer
}
}
Some Kotlin details in this code:
s[last] - 'A'subtracts twoCharvalues and gives anInt, which is what an array index needs.'B' - 'A'is1.count[index]++works on an array element directly.IntArrayis a primitive array ofIntthat starts filled with zeros.maxOf(a, b)returns the larger of two values, so noifis needed.s.indicesis the range0 until s.length.
Why maxCount is never lowered
When a letter leaves the window, the code decrements its counter but leaves maxCount alone. After that, maxCount can be larger than the true maximum inside the window. This is safe because the answer can only grow when the window gets a letter whose count beats 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.
Here is the run on s = "AABABBA" with k = 1:
last=0 char=A first=0 maxCount=1 window=A answer=1
last=1 char=A first=0 maxCount=2 window=AA answer=2
last=2 char=B first=0 maxCount=2 window=AAB answer=3
last=3 char=A first=0 maxCount=3 window=AABA answer=4
last=4 char=B first=1 maxCount=3 window=ABAB answer=4
last=5 char=B first=2 maxCount=3 window=BABB answer=4
last=6 char=A first=3 maxCount=3 window=ABBA answer=4
At last=4 the window ABAB holds two A's and two B's, so the true maximum is 2, but maxCount still says 3. The window only slides, at length 4, and the answer stays 4, which is correct.
Complexity
Time: O(n). last moves right once per character, and first only ever moves right, so the while body runs at most n times in total across the whole loop.
Space: O(1). The counter 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 run of one letter that already exists:"AABABBA"gives2, and"ABCD"gives1.kas large as the string. Every character can be changed, so the answer iss.length:"ABCD"withk = 4gives4.- One character.
"A"gives1, whateverkis. - Off-by-one in the length. The window from
firsttolastinclusive haslast - first + 1letters, notlast - first. - Recounting the maximum by scanning all 26 counters every time works, but it multiplies the time by 26. Keeping
maxCountavoids it.
Testing
ABAB k=2 -> 4
AABABBA k=1 -> 4
ABBBAABBBBA k=2 -> 9
AAAA k=0 -> 4
ABCD k=0 -> 1
ABCD k=4 -> 4
A k=0 -> 1
AABABBA k=0 -> 2
