Problem overview
The method characterReplacement(_ s: String, _ k: Int) 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 made of one 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". No single change gives a run of 5. For s = "ABBBAABBBBA" and k = 2 the answer is 9: changing the A's at indexes 4 and 5 turns indexes 1 to 9 into B's.
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
Instead of choosing the changes, look at substrings. A substring can become one repeated letter if the number of characters that are not its most common letter is at most k. Keep the most common letter and change the rest. So the question becomes: what is the longest window with length - (count of its most common letter) <= k?
Checking every substring and counting its letters would be far too slow for 100,000 characters. A sliding window avoids that. It has a left end first and a right end last, and it only moves right:
- Each turn adds the letter at
lastto the window. - If the window now needs more than
kchanges, the left end moves right until it needs at mostkagain. - After that, the window is valid, and its length is a candidate for the answer.
Both ends only move forward, so the two pointers together make at most about 2n moves, which is O(n).
Why maxCount is allowed to go stale
The code keeps maxCount, the largest count of one letter seen in a window. When the left end drops a letter, maxCount is not lowered, even though the real largest count in the window may now be smaller. That looks like a bug but is not. The answer only grows when a window gets longer than the best one so far. A longer valid window needs a letter whose count is bigger than the old maxCount, and that count is only reached by adding letters, which raises maxCount for real. A stale value can only keep the window from shrinking below the best length found, which does no harm.
Here is the run on "AABABBA" with k = 1. The columns show the state at the end of each turn of the loop:
last first maxCount window length answer
0 0 1 1 1
1 0 2 2 2
2 0 2 3 3
3 0 3 4 4
4 1 3 4 4
5 2 3 4 4
6 3 3 4 4
From last = 4 on, the window slides along at length 4. At last = 4 the real largest count in the window "ABAB" is 2, but maxCount still says 3. The answer stays 4 because no longer valid window exists.
Step by step
- Copy the letters into an array. A Swift
Stringcan't be indexed with an integer:s[0]is a compile error that says to use aString.Index.Array(s.utf8)gives the string as bytes, one per uppercase letter, andchars[i]is the code of the letter at indexi. - Create the counts.
countis an array of 26 zeros:count[0]counts the A's in the window,count[1]the B's, and so on. - Declare
maxCount, starting at 0. It holds the largest count of one letter in the window. - Declare
answerandfirst, both 0.firstis the window's left end, andansweris the longest valid window found so far. - Grow the window with a
forloop wherelastgoes over0..<chars.count. Each turn adds the letter atlast. - Turn the letter into a number from 0 to 25 with
Int(chars[last]) - 65, and add 1 to its count. 65 is the code ofA, and the codes of A to Z are consecutive. - Update
maxCountwithmax. Only the letter just added changed its count, so it is the only one that can beatmaxCount. - Shrink while the window is invalid.
last - first + 1is the window's length, and subtractingmaxCountleaves the letters that would have to change. Thewhileloop runs while that is greater thank. - Drop the first letter. Inside the loop, decrease its count and move
firstright by one. - Record the length. After the
while, the window needs at mostkchanges, soanswer = max(answer, last - first + 1). - Return
answerafter the loop.
The solution in Swift
class Solution {
func characterReplacement(_ s: String, _ k: Int) -> Int {
let chars = Array(s.utf8)
var count = [Int](repeating: 0, count: 26)
var maxCount = 0
var answer = 0, first = 0
for last in 0..<chars.count {
let index = Int(chars[last]) - 65
count[index] += 1
maxCount = max(maxCount, count[index])
while last - first + 1 - maxCount > k {
count[Int(chars[first]) - 65] -= 1
first += 1
}
answer = max(answer, last - first + 1)
}
return answer
}
}
The Swift details worth a closer look:
utf8yieldsUInt8values.Array(s.utf8)is a[UInt8]. Array indexes areInt, so the code converts each byte withInt(...)before subtracting 65. For"ABC"the array is[65, 66, 67], and after the conversion and subtraction it is[0, 1, 2].- Why not
Array(s)? That would give an array ofCharactervalues, which have no arithmetic. Bytes are simpler here because the input is limited to A to Z. [Int](repeating: 0, count: 26)builds an array of 26 zeros. Arrays are value types, socountmust be avarto change its elements.- Two declarations on one line.
var answer = 0, first = 0declares two separate variables, bothInt. - Ranges.
0..<chars.countexcludes the upper bound, and for an emptycharsit is an empty range. The loop variablelastis a constant inside each turn.
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. Converting the string to an array is also O(n).
Space: O(1) extra for the 26 counters and a few integers. The array chars holds a copy of the input, which is O(n), but it is there only to allow indexing.
Edge cases and common mistakes
k = 0. No changes are allowed, so the answer is the longest run of one letter that already exists."AAAA"gives 4,"ABCD"gives 1 and"AABABBA"gives 2.kequal to the length. Every character may change, so the whole string counts:"ABCD"withk = 4gives 4.- One character.
"A"withk = 0gives 1. - Forgetting
- 65. The byte forAis 65, so indexingcountwith it goes out of range, and Swift stops the program with an index-out-of-range error.
Testing
s = "ABAB",k = 2gives 4.s = "AABABBA",k = 1gives 4.s = "ABBBAABBBBA",k = 2gives 9.s = "AAAA",k = 0gives 4.s = "ABCD",k = 0gives 1.s = "ABCD",k = 4gives 4.
