Start learning free

LESSON 166 OF 314 · SLIDING WINDOW

Longest Repeating Character Replacement in C++: Sliding Window in 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

    C++ · SLIDING WINDOW

    Longest Repeating Character Replacement in C++, explained

    Problem overview

    The function characterReplacement receives a string s of uppercase letters and an integer k. You may change any character of s into any other uppercase letter, at most k times in total. The function returns the length of the longest substring made of one repeated letter that you can get this way.

    For s = "ABAB" and k = 2, changing both As gives "BBBB", so the answer is 4. For s = "AABABBA" and k = 1, changing the A at index 3 gives "AABBBBA", which holds "BBBB", and no single change gives a run of 5, so the answer is 4. For s = "ABBBAABBBBA" and k = 2, the answer is 9.

    The budget is O(n) time and constant extra space: one count for each of the 26 letters.

    Approach: a window that needs at most k changes

    Fix a substring. The cheapest way to turn it into one repeated letter is to keep its most common letter and change all the others. So a substring of length len whose most common letter appears maxCount times needs len - maxCount changes. It is a valid answer when len - maxCount <= k.

    Trying every substring and counting its letters is far too slow for 100,000 characters. A sliding window does it in one pass. The window runs from index first to index last and only moves right:

    1. Move last right by one, adding that letter to the window's counts.
    2. While the window needs more than k changes, drop its first letter and move first right.
    3. The window is now valid. Keep its length if it is the longest so far.

    Both ends only move right, so each moves at most n times and the whole run is O(n).

    There is one subtle shortcut. Keeping the exact largest count in the window would mean scanning the 26 counts after every removal. The lesson never lowers maxCount when a letter leaves. The value can then be larger than the real maximum, but this can't produce a wrong answer. A window only matters if it is longer than the best found so far. For a longer window to count, some letter must reach a count above the stale maxCount, and that raises maxCount to a true value. A stale value can only make the window stay at its current length instead of shrinking, never grow past a valid length.

    The trace for s = "AABABBA" and k = 1:

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

    At last = 3, the window "AABA" holds three As and needs one change, so it is valid, with length 4. At last = 4 the next B makes the window "AABAB", which needs 5 - 3 = 2 changes, so first moves right once. The remaining window "ABAB" shows the stale count at work: it really needs two changes, but maxCount is still 3, so the window is kept at length 4 and the answer doesn't grow. The result is 4, as expected.

    Step by step

    1. Create count, a vector<int> of 26 zeros: count[0] counts the As in the window, count[1] the Bs, and so on.
    2. Declare maxCount as 0. It tracks the largest count of one letter in the window.
    3. Declare answer and first as 0: the longest valid window so far and the window's left end.
    4. Loop last from 0 up to s.size(). Each turn adds the letter at last to the window.
    5. Compute index as s[last] - 'A', which is 0 for A, 1 for B and so on, because a char is a number in C++ and the uppercase letters are consecutive. Add 1 to count[index].
    6. Update maxCount with max(maxCount, count[index]). Only the letter just added changed its count, so only it can beat the old maximum.
    7. Shrink while the window is invalid. last - first + 1 - maxCount > k reads as: window length, minus the letters kept, is more than the allowed changes.
    8. Drop the first letter inside that loop: decrease count[s[first] - 'A'] and increase first. Leave maxCount alone, for the reason above.
    9. Update answer with max(answer, last - first + 1). After the shrinking, the window counts as one that needs at most k changes.
    10. Return answer.

    The solution in C++

    class Solution {
    public:
        int characterReplacement(string s, int k) {
            vector<int> count(26, 0);
            int maxCount = 0;
            int answer = 0, first = 0;
            for (int last = 0; last < s.size(); last++) {
                int index = s[last] - 'A';
                count[index]++;
                maxCount = max(maxCount, count[index]);
                while (last - first + 1 - maxCount > k) {
                    count[s[first] - 'A']--;
                    first++;
                }
                answer = max(answer, last - first + 1);
            }
            return answer;
        }
    };
    

    The C++ details worth a closer look:

    • char arithmetic. s[last] - 'A' subtracts two chars, and the result is an int. For uppercase letters it is in the range 0 to 25, a valid index for count. A lowercase letter would give a number from 32 up and write outside the vector, which is undefined behaviour. The constraints promise uppercase only.
    • vector<int> count(26, 0). The first argument is the size and the second the value of every element. Plain vector<int> count(26) would also give zeros.
    • max with two ints. max(a, b) from <algorithm> needs both arguments of the same type. count[index] and maxCount are both int.
    • Signed and unsigned. s.size() is unsigned, and last < s.size() compares an int with it. That is safe here because last is never negative, though some compilers warn. Don't write s.size() - 1 in a loop condition: for an empty string it wraps to a huge number.
    • The string is copied. s is taken by value. That costs O(n) once per call and doesn't change the complexity.

    Complexity

    Time: O(n). last visits each index once. first only moves right and never passes last, so the while body runs at most n times in total across the whole run, not per turn of the for. Each step is constant work.

    Space: O(1). The count vector always holds 26 integers, 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 already in s. "AAAB" with k = 0 gives 3, and "ABAB" with k = 0 gives 1.
    • k as large as the string. Every character can be changed, so the answer is s.size(): "ABC" with k = 3 gives 3.
    • A single character. "A" with k = 0 gives 1.
    • One letter only. A string of 100,000 Zs with k = 0 gives 100000: the window never shrinks.
    • Counting changes as the number of letters different from the first. The cheapest plan keeps the most common letter of the window, which may not be the first or the last one.
    • Recomputing the maximum on every step. It is correct, but it adds a scan of 26 counts to every step, which the stale maxCount makes unnecessary.
    • Forgetting to decrease count when a letter leaves. The counts would describe more than the window, and maxCount would be inflated.

    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 = "ABAB", k = 0 gives 1.
    • s = "ABC", k = 3 gives 3.
    • s = "A", k = 0 gives 1.
    Keep going with C++1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free