Start learning free

LESSON 166 OF 314 · SLIDING WINDOW

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

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

    GO · SLIDING WINDOW

    Longest Repeating Character Replacement in Go, explained

    Problem overview

    The function characterReplacement receives a string s of uppercase letters and an integer k. You may change at most k characters, each into any uppercase letter. The function returns the length of the longest substring made of one repeated letter that you can get this way. A substring is a run of consecutive characters.

    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 makes a run of 5. For s = "ABBBAABBBBA" and k = 2 the answer is 9: change the two As at indexes 4 and 5, and indexes 1 to 9 all become B.

    The target is O(n) time and O(1) extra space, where the space is one counter for each of the 26 letters.

    Approach: a window that needs at most k changes

    Think of a window, the substring from index first to index last. If you want the whole window to become one letter, the cheapest plan is to keep its most common letter and change every other one. The number of changes is therefore:

    window length - count of the most common letter

    A window is good when that number is at most k. The answer is the length of the longest good window.

    Trying every substring and counting its letters would be far too slow for 100,000 characters. The sliding window avoids that. The right end last moves one step at a time and adds a letter. If the window now needs more than k changes, the left end first moves right until it is good again. Both ends only move forward, so each moves at most n times and the total work is O(n).

    Step by step

    1. Make 26 counters. make([]int, 26) creates a slice of zeros. Position 0 counts the As in the window, position 1 the Bs, and so on.
    2. Track maxCount, the largest count of one letter in the window, starting at 0.
    3. Start with an empty window. answer is the best length so far and first is the left end; both are 0.
    4. Grow to the right. A for loop moves last from 0 to len(s) - 1, and every turn adds the letter at last.
    5. Count the new letter. s[last] is a byte holding the letter's code. The codes of A to Z are consecutive, so subtracting 'A' turns a letter into a number from 0 to 25, which indexes count.
    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 bad. The window length is last-first+1. Subtract maxCount and what is left is the number of letters to change. While that exceeds k, the inner loop runs. Go has no while, so this is a for with only a condition.
    8. Drop the first letter. Decrease its counter and move first right.
    9. Record the length. Now the window needs at most k changes, so answer becomes the larger of itself and the window length.
    10. Return answer.

    The solution in Go

    func characterReplacement(s string, k int) int {
        count := make([]int, 26)
        maxCount := 0
        answer, first := 0, 0
        for last := 0; last < len(s); last++ {
            index := s[last] - 'A'
            count[index]++
            maxCount = max(maxCount, count[index])
            for last-first+1-maxCount > k {
                count[s[first]-'A']--
                first++
            }
            answer = max(answer, last-first+1)
        }
        return answer
    }
    

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

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

    Each row shows the window after the shrinking step. The window grows to length 4 at last=3. After that it slides along at length 4, because every longer window would need two changes.

    Why maxCount is never lowered

    When a letter leaves the window, the code decreases its counter but leaves maxCount alone, so maxCount can be larger than the real maximum. At last=4 above, the window "ABAB" has a real maximum of 2, yet maxCount is still 3. That is safe. A stale value can only make the window look better than it is, and the only effect is that the window slides along at its current length instead of shrinking. The answer can grow only when the window gets longer, and a longer good window needs a letter whose count really exceeds the old maximum. That raises maxCount for real. So answer never takes a length that is not achievable.

    Go details

    • s[last] is a byte. Indexing a string gives a byte (uint8), not a character. s[last] - 'A' is therefore a byte too, from 0 to 25 for uppercase letters. Go accepts it as a slice index, because any integer type can index a slice.
    • := and the multiple assignment. answer, first := 0, 0 declares both variables at once, as ints.
    • max. Since Go 1.21, max is built in and works on any two ordered values of the same type. There is nothing to import.
    • for is the only loop. The outer for has the three parts (start, condition, step), and the inner one has only a condition, which is how Go writes a while loop.
    • len(s) counts bytes. That equals the number of letters here, because the input contains only A to Z.

    Complexity

    Time: O(n). last visits each index once. first only moves right and never passes last, so the inner loop's body runs at most n times in total across the whole run.

    Space: O(1). The slice has 26 integers whatever the length of the string, plus a few integer variables.

    Edge cases and common mistakes

    • k = 0. No changes are allowed, so the answer is the longest run of one letter that is already there. "BAAAB" gives 3, and "ABC" gives 1.
    • k equals the length. Every character can be changed, so "ABC" with k = 3 gives 3.
    • One character. "A" with k = 0 gives 1.
    • A string that is already one letter. "AAAA" with k = 0 gives 4, and the inner loop never runs.
    • Recomputing the maximum over 26 counters every turn. It is still linear, but it is unnecessary, because only the new letter can raise it.
    • Forgetting to subtract 'A'. A letter's raw code is 65 to 90, which is outside a slice of 26 elements and panics with an index out of range error.
    • Measuring the window as last-first. The length of a window that includes both ends is last-first+1.

    Testing

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