Problem overview
The function character_replacement receives a string s of uppercase letters and an integer k. You may change at most k characters of s, each into any uppercase letter. The function returns the length of the longest substring made of one repeated letter that you can end up with.
For 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 AAAA instead, and no single change gives a run of 5. For "ABAB" with k = 2 the answer is 4, and for "ABBBAABBBBA" with k = 2 it is 9.
Approach: a window that needs at most k changes
Look at any substring. The cheapest way to turn it into one repeated letter is to keep its most common letter and change every other character. The number of changes is therefore:
window length - count of the most common letter in the window
A substring is a valid answer exactly when that number is at most k. So the task becomes: find the longest window with length - max_count <= k.
A sliding window finds it in one pass. The right end last moves over the string one character at a time, adding each letter to the window. When the window needs more than k changes, the left end first moves right until it is valid again. Both ends only move right, so the work is O(n), and the only extra memory is one count for each of the 26 letters, which is O(1). Trying every substring and counting letters would be far slower.
Why max_count may be stale
When a letter leaves the window, the code doesn't lower max_count, even though the true maximum may have dropped. This is safe. A stale max_count can only make a window look cheaper than it is, so the window may stay at its current length without being truly valid. But the answer is the largest window length ever reached, and a window can only grow beyond its current length when some letter's count really exceeds the old max_count, which raises max_count for real. So the answer is never larger than a truly valid window allows.
For "AABABBA" with k = 1, the window printed after each step is:
| last | window | max_count | answer |
|---|---|---|---|
| 0 | A | 1 | 1 |
| 1 | AA | 2 | 2 |
| 2 | AAB | 2 | 3 |
| 3 | AABA | 3 | 4 |
| 4 | ABAB | 3 | 4 |
| 5 | BABB | 3 | 4 |
| 6 | ABBA | 3 | 4 |
From last = 4 on, the window keeps length 4 and slides along the string. Its real maximum count is only 2, so it is not a valid window with k = 1, but max_count still says 3. It makes no difference to the answer: the window never grows to 5, because that would need a letter with a count of 4.
Step by step
- Get the bytes.
s.as_bytes()gives a&[u8]that can be indexed by number. Every uppercase letter is one byte. - Create the counts.
[0i32; 26]is a fixed array of 26 zeros: index 0 counts the A's in the window, index 1 the B's, and so on. - Track
max_count, the largest count of one letter seen in the window, starting at 0. - Set up
answerandfirst.answeris ani32because the function returns one.firstis the window's left end, an index, so it is ausize. - Loop
lastover0..bytes.len(), which adds one letter to the window per turn. - Convert the letter to an index.
bytes[last] - b'A'is 0 for A, 1 for B and so on, andas usizemakes it usable as an array index. Add 1 to that count. - Update
max_countwithmax_count.max(count[index]). Only the letter just added changed, so only it can beat the old maximum. - Shrink while the window is too costly.
(last - first + 1) as i32 - max_count > kcompares the number of changes withk. The window length is ausize, so it is cast toi32to matchmax_countandk. - Drop the first letter inside that loop: decrease its count and move
firstright. - Record the length. After the
while, the window passes the cost test as far as the code can tell, soanswerbecomes the larger of itself and the window length. - Return
answeras the last expression, with no semicolon.
The solution in Rust
impl Solution {
fn character_replacement(s: String, k: i32) -> i32 {
let bytes = s.as_bytes();
let mut count = [0i32; 26];
let mut max_count = 0i32;
let mut answer = 0i32;
let mut first = 0usize;
for last in 0..bytes.len() {
let index = (bytes[last] - b'A') as usize;
count[index] += 1;
max_count = max_count.max(count[index]);
while (last - first + 1) as i32 - max_count > k {
count[(bytes[first] - b'A') as usize] -= 1;
first += 1;
}
answer = answer.max((last - first + 1) as i32);
}
answer
}
}
The Rust details worth a closer look:
- Bytes, not characters. Indexing a
Stringwith a number doesn't compile, but a byte slice can be indexed. That is fine here because the input is plain uppercase ASCII. - Byte arithmetic.
b'A'is au8literal, the value 65.bytes[last] - b'A'is au8subtraction, which would underflow for a character belowA. For a lowercase letter it gives a number of 32 or more, which is outside the 26-element array and panics when used as an index. - Casts to
i32. Rust never converts between integer types implicitly, so(last - first + 1) as i32is needed before subtractingmax_count. Inputs are at most 100,000 long, so the cast loses nothing. last - first + 1never underflows.firstnever passeslast: a window of one letter always needs 0 changes, so thewhilestops before it empties the window.- The
maxmethod.a.max(b)comes from theOrdtrait and works on integers, which is shorter than anifand an assignment.
Complexity
Time: O(n). last takes n values, and first only moves right, so across the whole run the while body executes at most n times. Each step costs a constant amount.
Space: O(1). The array has 26 entries whatever the length of the string.
Edge cases and common mistakes
k = 0. No change is allowed, so the answer is the longest run that already exists."ABAB"withk = 0gives 1, and"AAAA"withk = 0gives 4.- A large
k. Whenkis at least the length minus 1, the whole string can be changed:"ABCD"withk = 3gives 4. The window never shrinks. - A single character.
"A"withk = 0gives 1. - Recomputing the maximum on every shrink. Scanning the 26 counts each time is also correct, but it isn't needed.
- Forgetting to subtract
b'A'. The byte value 65 would be used as an index into a 26-element array, which panics.
Testing
s = "ABAB",k = 2gives4.s = "AABABBA",k = 1gives4.s = "ABBBAABBBBA",k = 2gives9.s = "ABAB",k = 0gives1.s = "ABCD",k = 3gives4.s = "A",k = 0gives1.
