Start learning free

LESSON 166 OF 314 · SLIDING WINDOW

Longest Repeating Character Replacement in Swift: 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

    SWIFT · SLIDING WINDOW

    Longest Repeating Character Replacement in Swift, explained

    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 last to the window.
    • If the window now needs more than k changes, the left end moves right until it needs at most k again.
    • 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

    1. Copy the letters into an array. A Swift String can't be indexed with an integer: s[0] is a compile error that says to use a String.Index. Array(s.utf8) gives the string as bytes, one per uppercase letter, and chars[i] is the code of the letter at index i.
    2. Create the counts. count is an array of 26 zeros: count[0] counts the A's in the window, count[1] the B's, and so on.
    3. Declare maxCount, starting at 0. It holds the largest count of one letter in the window.
    4. Declare answer and first, both 0. first is the window's left end, and answer is the longest valid window found so far.
    5. Grow the window with a for loop where last goes over 0..<chars.count. Each turn adds the letter at last.
    6. 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 of A, and the codes of A to Z are consecutive.
    7. Update maxCount with max. Only the letter just added changed its count, so it is the only one that can beat maxCount.
    8. Shrink while the window is invalid. last - first + 1 is the window's length, and subtracting maxCount leaves the letters that would have to change. The while loop runs while that is greater than k.
    9. Drop the first letter. Inside the loop, decrease its count and move first right by one.
    10. Record the length. After the while, the window needs at most k changes, so answer = max(answer, last - first + 1).
    11. Return answer after 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:

    • utf8 yields UInt8 values. Array(s.utf8) is a [UInt8]. Array indexes are Int, so the code converts each byte with Int(...) 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 of Character values, 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, so count must be a var to change its elements.
    • Two declarations on one line. var answer = 0, first = 0 declares two separate variables, both Int.
    • Ranges. 0..<chars.count excludes the upper bound, and for an empty chars it is an empty range. The loop variable last is 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.
    • k equal to the length. Every character may change, so the whole string counts: "ABCD" with k = 4 gives 4.
    • One character. "A" with k = 0 gives 1.
    • Forgetting - 65. The byte for A is 65, so indexing count with it goes out of range, and Swift stops the program with an index-out-of-range error.

    Testing

    • s = "ABAB", k = 2 gives 4.
    • s = "AABABBA", k = 1 gives 4.
    • s = "ABBBAABBBBA", k = 2 gives 9.
    • s = "AAAA", k = 0 gives 4.
    • s = "ABCD", k = 0 gives 1.
    • s = "ABCD", k = 4 gives 4.
    Keep going with Swift1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free