Start learning free

LESSON 166 OF 314 · SLIDING WINDOW

Longest Repeating Character Replacement in Rust: O(n) Sliding Window

Practice O(n) Read the full explanation

You are given a string s made of uppercase English letters and an integer k. You can pick any character of s and change it into any other uppercase letter. You can do this at most k times.

Return the length of the longest substring made of one repeated letter that you can get after these changes.

A substring is a run of consecutive characters of s.

 

Example 1:

Input: s = "ABAB", k = 2
Output: 4
Explanation: Change both A's into B's to get "BBBB", or both B's into A's to get "AAAA".

Example 2:

Input: s = "AABABBA", k = 1
Output: 4
Explanation: Change the A at index 3 into a B to get "AABBBBA": the substring "BBBB" has length 4. Changing the B at index 2 gives "AAAA" instead. No single change gives a run of 5.

Example 3:

Input: s = "ABBBAABBBBA", k = 2
Output: 9
Explanation: Change the A's at indexes 4 and 5 into B's: indexes 1 to 9 become "BBBBBBBBB". Any longer substring holds a third A.

 

Constraints:

  • 1 <= s.length <= 105
  • s is made of uppercase English letters only (A to Z).
  • 0 <= k <= s.length

Note:

Your algorithm should run in O(n) time, where n is the length of s, and use O(1) extra space: one count for each of the 26 letters.

STEP 1 OF 11
    Ctrl + Enter to check

    RUST · SLIDING WINDOW

    Longest Repeating Character Replacement in Rust, explained

    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:

    lastwindowmax_countanswer
    0A11
    1AA22
    2AAB23
    3AABA34
    4ABAB34
    5BABB34
    6ABBA34

    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

    1. Get the bytes. s.as_bytes() gives a &[u8] that can be indexed by number. Every uppercase letter is one byte.
    2. 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.
    3. Track max_count, the largest count of one letter seen in the window, starting at 0.
    4. Set up answer and first. answer is an i32 because the function returns one. first is the window's left end, an index, so it is a usize.
    5. Loop last over 0..bytes.len(), which adds one letter to the window per turn.
    6. Convert the letter to an index. bytes[last] - b'A' is 0 for A, 1 for B and so on, and as usize makes it usable as an array index. Add 1 to that count.
    7. Update max_count with max_count.max(count[index]). Only the letter just added changed, so only it can beat the old maximum.
    8. Shrink while the window is too costly. (last - first + 1) as i32 - max_count > k compares the number of changes with k. The window length is a usize, so it is cast to i32 to match max_count and k.
    9. Drop the first letter inside that loop: decrease its count and move first right.
    10. Record the length. After the while, the window passes the cost test as far as the code can tell, so answer becomes the larger of itself and the window length.
    11. Return answer as 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 String with 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 a u8 literal, the value 65. bytes[last] - b'A' is a u8 subtraction, which would underflow for a character below A. 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 i32 is needed before subtracting max_count. Inputs are at most 100,000 long, so the cast loses nothing.
    • last - first + 1 never underflows. first never passes last: a window of one letter always needs 0 changes, so the while stops before it empties the window.
    • The max method. a.max(b) comes from the Ord trait and works on integers, which is shorter than an if and 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" with k = 0 gives 1, and "AAAA" with k = 0 gives 4.
    • A large k. When k is at least the length minus 1, the whole string can be changed: "ABCD" with k = 3 gives 4. The window never shrinks.
    • A single character. "A" with k = 0 gives 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 = 2 gives 4.
    • s = "AABABBA", k = 1 gives 4.
    • s = "ABBBAABBBBA", k = 2 gives 9.
    • s = "ABAB", k = 0 gives 1.
    • s = "ABCD", k = 3 gives 4.
    • s = "A", k = 0 gives 1.
    Keep going with Rust1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free