Start learning free

LESSON 166 OF 314 · SLIDING WINDOW

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

    PYTHON · SLIDING WINDOW

    Longest Repeating Character Replacement in Python, explained

    Problem overview

    The method characterReplacement receives a string s of uppercase letters and an integer k. You may change any character into any other uppercase letter, at most k times in total. The method returns the length of the longest substring made of a single 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 gives "AABBBBA", which holds "BBBB". Changing the B at index 2 gives "AAAA" instead. No single change reaches 5. For s = "ABBBAABBBBA" and k = 2 the answer is 9: changing the two As at indexes 4 and 5 turns indexes 1 to 9 into Bs.

    Approach: a window that needs at most k changes

    Look at one window, a substring from index first to index last. The cheapest way to make it one letter is to keep its most common letter and change every other one. So the number of changes needed is the window's length minus the count of its most common letter. The window is good when that number is at most k, and the answer is the length of the longest good window.

    That suggests a sliding window. Move last to the right one character at a time, which adds a letter to the window. If the window now needs more than k changes, move first to the right until it needs at most k again. Both ends only move right, so each index enters and leaves the window at most once, and the whole scan is O(n). Checking every substring would take O(n²) windows, which is too slow for 100,000 characters.

    The counts live in a list of 26 integers, one per letter, so the extra space is O(1).

    Here is the scan on "AABABBA" with k = 1:

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

    At last=4 the window "AABAB" would need 5 - 3 = 2 changes, more than k, so first moves one step right and the window becomes "ABAB".

    Step by step

    1. Create count as [0] * 26. Slot 0 counts the As in the window, slot 1 the Bs, and so on.
    2. Create maxCount at 0. It holds the largest count of one letter seen in the window.
    3. Set answer = first = 0. first is the window's left end, and answer is the longest good window so far.
    4. Loop last over range(len(s)). Each turn adds the letter at last to the window.
    5. Convert the letter to a slot number with ord(s[last]) - ord('A'), then add 1 to that count. Letters have consecutive codes, so A maps to 0 and Z to 25.
    6. Update maxCount with max. Only the letter just added changed its count, so it is the only one that can set a new maximum.
    7. Shrink while the window is too costly. The window's length is last - first + 1. Subtract maxCount to get the number of changes, and loop while that exceeds k.
    8. Drop the first letter: subtract 1 from its count and add 1 to first.
    9. Record the window's length in answer with max. At this point the window needs at most k changes.
    10. Return answer.

    The solution in Python

    class Solution:
        def characterReplacement(self, s: str, k: int) -> int:
            count = [0] * 26
            maxCount = 0
            answer = first = 0
            for last in range(len(s)):
                index = ord(s[last]) - ord('A')
                count[index] += 1
                maxCount = max(maxCount, count[index])
                while last - first + 1 - maxCount > k:
                    count[ord(s[first]) - ord('A')] -= 1
                    first += 1
                answer = max(answer, last - first + 1)
            return answer
    

    Details worth a closer look:

    • Chained assignment. answer = first = 0 gives both names the integer 0. Integers are immutable, so later changes to one name never affect the other. The same line with a list would make both names refer to one shared list, which is why count is created on its own line.
    • [0] * 26 builds a list of 26 zeros. This is safe for integers, because adding 1 to count[index] replaces that slot with a new integer.
    • ord turns a one-character string into its code. ord('B') - ord('A') is 1. Indexing a string, as in s[last], gives a one-character string.
    • Why maxCount is never lowered. When a letter leaves the window, maxCount can be larger than the true maximum. In the trace, after "AABAB" shrinks to "ABAB", the true maximum is 2 while maxCount stays 3. That is harmless: a stale value can only stop the window from shrinking, so the window keeps the length of the best one found so far, and answer doesn't grow. To beat the current answer, a later window needs a letter whose count exceeds the stale value, and then maxCount rises for real.

    Complexity

    Time: O(n). The for loop runs n times. The while loop moves first to the right and first never moves back, so across the whole run its body executes at most n times in total. Everything else is constant work.

    Space: O(1). The list always has 26 slots, whatever the length of s.

    Edge cases and common mistakes

    • No changes allowed. With k = 0 the answer is the longest run of one repeated letter: "AAAA" gives 4 and "ABC" gives 1.
    • k as large as the string. "ABC" with k = 3 gives 3, the whole string.
    • A single character. "A" with k = 0 gives 1.
    • Counting changes the wrong way. The cost is the window length minus the largest count, not minus the count of the letter at last.
    • Off-by-one window length. The length of the window from first to last inclusive is last - first + 1.
    • Recounting the window. Scanning the 26 counts or the window for its maximum on every step also works, but it is wasted effort here. The running maxCount is enough for the answer.
    • Forgetting to decrement. If the dropped letter's count is not reduced, the counts no longer describe the window and the answer comes out too large.

    Testing

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