Start learning free

LESSON 166 OF 314 · SLIDING WINDOW

Longest Repeating Character Replacement in Scala: 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 10
    Ctrl + Enter to check

    SCALA · SLIDING WINDOW

    Longest Repeating Character Replacement in Scala, explained

    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:

    lastwindowfirstmaxCountanswer
    0A011
    1AA022
    2AAB023
    3AABA034
    4ABAB134
    5BABB234
    6ABBA334

    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

    1. Create the counters. Array.fill(26)(0) makes an array of 26 zeros in a val. A val array can still change its elements. count(0) holds the A's in the window, count(1) the B's, and so on.
    2. Declare maxCount. A var starting at 0, for the largest count of one letter seen in a window.
    3. Declare answer and first. Both are vars starting at 0. The window begins empty at the left end of s.
    4. Grow the window to the right. for (last <- s.indices) visits every index from 0 to the last. Each turn adds the letter at last.
    5. 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 in index, and count(index) += 1 records the letter.
    6. Update maxCount. Only the letter just added changed its count, so it is the only one that can beat maxCount. math.max keeps the larger value.
    7. Shrink while the window is too costly. last - first + 1 is the window's length. Subtracting maxCount leaves the letters to change. While that is greater than k, the window is invalid.
    8. Drop the left letter. Subtract 1 from its count and move first right. maxCount stays as it is.
    9. Record the window. After the while, the window needs at most k changes, so its length is a candidate for answer.
    10. Return answer as 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), not count[index]. The same goes for characters of a string: s(last) is a Char.
    • Char - Char is an Int. 'B' - 'A' is the Int 1, which is exactly what an array index needs. There is no cast.
    • count(index) += 1 on a val. The expression is shorthand for count.update(index, count(index) + 1). It changes an element, not the reference, so it is allowed.
    • s.indices. It is the range 0 until s.length, so the loop variable is an Int and the loop never runs for an empty string.
    • The result. The final answer is the value of the block, so no return is 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.
    • k at least the length of the string. Every character can be changed, so the answer is the length of s. "ABCD" with k = 4 gives 4.
    • A single character. "A" with k = 0 gives 1.
    • Recomputing the maximum on every shrink. Scanning the 26 counters again is still O(1) per step, but it is unnecessary here. The stale maxCount never produces a wrong answer.
    • Forgetting the + 1. The window from first to last inclusive has last - first + 1 letters. Without the + 1, every length is one too small.
    • Using an if instead of a while. The inner loop is a while so 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, but while states 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 an ArrayIndexOutOfBoundsException.

    Testing

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