Start learning free

LESSON 166 OF 314 · SLIDING WINDOW

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

    KOTLIN · SLIDING WINDOW

    Longest Repeating Character Replacement in Kotlin, 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 uppercase letters. The function returns the length of the longest substring made of a single 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". For "ABAB" with k = 2 the whole string can become one letter, so the answer is 4. For "ABBBAABBBBA" with k = 2 the answer is 9.

    The statement asks for O(n) time and O(1) extra space: one counter for each of the 26 letters.

    Approach

    Trying every substring and counting its letters would take at least O(n²) time. The faster idea looks at windows, meaning runs of consecutive characters between two indexes, first and last.

    For a given window, the cheapest plan is to keep its most common letter and change every other letter. That costs window length - count of the most common letter changes. The window is usable when that number is at most k.

    So the algorithm grows the window one character at a time on the right. When the window needs more than k changes, it shrinks from the left until it is valid again. The best answer is the largest length a valid window ever had. Each index enters the window once and leaves at most once, so the work is O(n).

    The window does not have to be valid at every moment on its way to the answer. It only has to be valid when its length is recorded. In the run on "AABABBA" with k = 1 (shown below), the window reaches "AABA", which has three A's and one B: one change makes it all A's, so its length 4 is recorded. Adding the next B would make the window need two changes, so the left end moves right by one.

    A window of length 5 would need a letter that appears 4 times, and no window of 5 has one, so the answer stays 4. The trace below shows how the counters get there.

    Step by step

    1. Create count, an IntArray(26) that starts with 26 zeros. count[0] counts the A's in the window, count[1] the B's, and so on.
    2. Create maxCount, starting at 0: the largest count of one letter seen in the window.
    3. Create answer and first, both starting at 0. first is the left end of the window.
    4. Loop last over s.indices. Each turn adds the letter at last to the window.
    5. Convert the new letter to an index. Subtracting two Char values gives an Int, and the letters A to Z are consecutive, so s[last] - 'A' is 0 for A, 1 for B, and so on. Then add 1 to that counter.
    6. Update maxCount. Only the letter just added changed its count, so it is the only one that can beat the old maximum.
    7. Shrink while the window is too expensive. The window has last - first + 1 letters. Take away maxCount and the rest are the letters to change. While that is more than k, the window is invalid.
    8. Drop the first letter inside that loop: decrease its counter and move first right by one.
    9. Record the length. After shrinking, the window is valid, so answer becomes the larger of itself and last - first + 1.
    10. Return answer.

    The solution in Kotlin

    class Solution {
        fun characterReplacement(s: String, k: Int): Int {
            val count = IntArray(26)
            var maxCount = 0
            var answer = 0
            var first = 0
            for (last in s.indices) {
                val index = s[last] - 'A'
                count[index]++
                maxCount = maxOf(maxCount, count[index])
                while (last - first + 1 - maxCount > k) {
                    count[s[first] - 'A']--
                    first++
                }
                answer = maxOf(answer, last - first + 1)
            }
            return answer
        }
    }
    

    Some Kotlin details in this code:

    • s[last] - 'A' subtracts two Char values and gives an Int, which is what an array index needs. 'B' - 'A' is 1.
    • count[index]++ works on an array element directly. IntArray is a primitive array of Int that starts filled with zeros.
    • maxOf(a, b) returns the larger of two values, so no if is needed.
    • s.indices is the range 0 until s.length.

    Why maxCount is never lowered

    When a letter leaves the window, the code decrements its counter but leaves maxCount alone. After that, maxCount can be larger than the true maximum inside the window. This is safe because the answer can only grow when the window gets a letter whose count beats the old maxCount, and that raises maxCount for real. A stale value can only keep the window from shrinking below the best length already found.

    Here is the run on s = "AABABBA" with k = 1:

    last=0 char=A first=0 maxCount=1 window=A answer=1
    last=1 char=A first=0 maxCount=2 window=AA answer=2
    last=2 char=B first=0 maxCount=2 window=AAB answer=3
    last=3 char=A first=0 maxCount=3 window=AABA answer=4
    last=4 char=B first=1 maxCount=3 window=ABAB answer=4
    last=5 char=B first=2 maxCount=3 window=BABB answer=4
    last=6 char=A first=3 maxCount=3 window=ABBA answer=4
    

    At last=4 the window ABAB holds two A's and two B's, so the true maximum is 2, but maxCount still says 3. The window only slides, at length 4, and the answer stays 4, which is correct.

    Complexity

    Time: O(n). last moves right once per character, and first only ever moves right, so the while body runs at most n times in total across the whole loop.

    Space: O(1). The counter array has 26 entries whatever the length of s.

    Edge cases and common mistakes

    • k = 0. No changes are allowed, so the answer is the longest run of one letter that already exists: "AABABBA" gives 2, and "ABCD" gives 1.
    • k as large as the string. Every character can be changed, so the answer is s.length: "ABCD" with k = 4 gives 4.
    • One character. "A" gives 1, whatever k is.
    • Off-by-one in the length. The window from first to last inclusive has last - first + 1 letters, not last - first.
    • Recounting the maximum by scanning all 26 counters every time works, but it multiplies the time by 26. Keeping maxCount avoids it.

    Testing

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