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 other uppercase letters. The function returns the length of the longest substring made of one repeated letter that you can get this way.
With 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 a run of four A's instead. No single change gives a run of five. With "ABAB" and k = 2 the whole string can become one letter, so the answer is 4.
The statement asks for 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
Take any substring. The cheapest way to turn it into one repeated letter is to keep its most common letter and change every other character. So a substring of length len whose most common letter appears maxCount times needs len - maxCount changes, and it is a valid answer when that number is at most k.
Checking every substring and counting its letters is far too slow for a string of 100,000 characters. A sliding window avoids it. The window runs from index first to index last. The right end last moves one step at a time over the whole string, and the left end first only ever moves right, and only when the window needs more than k changes. Both ends travel across the string once, so the work is linear.
The counts of the 26 letters inside the window are kept in an array and updated as letters enter and leave.
The lesson uses one well-known simplification: maxCount is never lowered when a letter leaves the window. It can then be larger than the true maximum inside the window. This is harmless. The window only has to avoid shrinking below the best length already found, and a longer window than the current answer needs a letter whose real count exceeds the stale maxCount. When that happens, maxCount is raised for real.
Here is "AABABBA" with k = 1, after each new letter has been added and the window has been shrunk where necessary:
| last | window | first | maxCount | answer |
|---|---|---|---|---|
| 0 | A | 0 | 1 | 1 |
| 1 | AA | 0 | 2 | 2 |
| 2 | AAB | 0 | 2 | 3 |
| 3 | AABA | 0 | 3 | 4 |
| 4 | ABAB | 1 | 3 | 4 |
| 5 | BABB | 2 | 3 | 4 |
| 6 | ABBA | 3 | 3 | 4 |
From index 4 on, the window slides along at length 4: each new letter pushes the window past the allowed number of changes, so exactly one letter leaves on the left.
Step by step
- Create the counters.
Array.fill(26)(0)makes an array of 26 zeros in aval. Avalarray can still change its elements.count(0)holds the A's in the window,count(1)the B's, and so on. - Declare
maxCount. Avarstarting at 0, for the largest count of one letter seen in a window. - Declare
answerandfirst. Both arevars starting at 0. The window begins empty at the left end ofs. - Grow the window to the right.
for (last <- s.indices)visits every index from 0 to the last. Each turn adds the letter atlast. - Count the new letter.
s(last) - 'A'turns the letter into a number from 0 to 25, because the uppercase letters have consecutive character codes. It is stored inindex, andcount(index) += 1records the letter. - Update
maxCount. Only the letter just added changed its count, so it is the only one that can beatmaxCount.math.maxkeeps the larger value. - Shrink while the window is too costly.
last - first + 1is the window's length. SubtractingmaxCountleaves the letters to change. While that is greater thank, the window is invalid. - Drop the left letter. Subtract 1 from its count and move
firstright.maxCountstays as it is. - Record the window. After the
while, the window needs at mostkchanges, so its length is a candidate foranswer. - Return
answeras the last expression of the method.
The solution in Scala
class Solution {
def characterReplacement(s: String, k: Int): Int = {
val count = Array.fill(26)(0)
var maxCount = 0
var answer = 0
var first = 0
for (last <- s.indices) {
val index = s(last) - 'A'
count(index) += 1
maxCount = math.max(maxCount, count(index))
while (last - first + 1 - maxCount > k) {
count(s(first) - 'A') -= 1
first += 1
}
answer = math.max(answer, last - first + 1)
}
answer
}
}
The Scala details worth a closer look:
- Arrays use parentheses. Scala reads an element with
count(index), notcount[index]. The same goes for characters of a string:s(last)is aChar. Char - Charis anInt.'B' - 'A'is theInt1, which is exactly what an array index needs. There is no cast.count(index) += 1on aval. The expression is shorthand forcount.update(index, count(index) + 1). It changes an element, not the reference, so it is allowed.s.indices. It is the range0 until s.length, so the loop variable is anIntand the loop never runs for an empty string.- The result. The final
answeris the value of the block, so noreturnis needed.
Complexity
Time: O(n). The for loop runs n times. The inner while loop moves first right by one each time its body runs, and first never moves left or passes last, so across the whole call its body runs at most n times.
Space: O(1). The 26-element array does not depend on the length of s.
Edge cases and common mistakes
k = 0. The window may not change anything, so the answer is the longest run of one letter that already exists:"AAAB"gives 3 and"ABCD"gives 1.kat least the length of the string. Every character can be changed, so the answer is the length ofs."ABCD"withk = 4gives 4.- A single character.
"A"withk = 0gives 1. - Recomputing the maximum on every shrink. Scanning the 26 counters again is still
O(1)per step, but it is unnecessary here. The stalemaxCountnever produces a wrong answer. - Forgetting the
+ 1. The window fromfirsttolastinclusive haslast - first + 1letters. Without the+ 1, every length is one too small. - Using an
ifinstead of awhile. The inner loop is awhileso the window can shrink as far as needed. In this problem a window is never more than one letter too long, so one step is enough, butwhilestates the rule directly. - Counting letters with
s(last).toInt. Without subtracting'A', the index would be 65 or more and the array of 26 would throw anArrayIndexOutOfBoundsException.
Testing
s = "ABAB",k = 2gives4.s = "AABABBA",k = 1gives4.s = "ABBBAABBBBA",k = 2gives9.s = "AAAB",k = 0gives3.s = "ABCD",k = 0gives1.s = "ABCD",k = 4gives4.
