Start learning free

LESSON 166 OF 314 · SLIDING WINDOW

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

    C# · SLIDING WINDOW

    Longest Repeating Character Replacement in C#, explained

    Problem overview

    The method 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 method returns the length of the longest substring that consists of a single repeated letter after those changes.

    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 produces a run of 5. For "ABAB" with k = 2 the whole string can become one letter, so the answer is 4.

    The target is 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

    Instead of thinking about which characters to change, think about which substrings could become a single letter. A substring can become one repeated letter if the number of characters that differ from its most common letter is at most k. The best plan for any substring is to keep its most common letter and change all the others, so its cost is length - (count of the most common letter).

    That turns the task into: find the longest window whose length minus its largest letter count is at most k. A sliding window does this in one pass. The right end last moves forward one character at a time. When the window becomes too expensive, the left end first moves forward until it is acceptable again. Both ends only move right, so each character enters and leaves at most once.

    Trying every substring and counting its letters would take O(n²) or worse. The window reuses its counts, adding the new letter and removing the old one, so each move costs O(1).

    One detail is the largest count, maxCount. When a letter leaves the window, the code doesn't lower maxCount, even though it may now be larger than the real maximum. This is safe. The answer only grows when the window finds a longer valid length, which needs a letter whose count exceeds 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, and that length is already recorded in answer.

    Here is the run on "AABABBA" with k = 1, printing the window start, maxCount and answer after each step of last:

    last=0 first=0 maxCount=1 answer=1
    last=1 first=0 maxCount=2 answer=2
    last=2 first=0 maxCount=2 answer=3
    last=3 first=0 maxCount=3 answer=4
    last=4 first=1 maxCount=3 answer=4
    last=5 first=2 maxCount=3 answer=4
    last=6 first=3 maxCount=3 answer=4
    

    At last = 4 the window "AABAB" has length 5 and maxCount = 3, so it needs 2 changes. That is more than k = 1, so first moves to 1. From then on the window keeps length 4, and the answer stays 4.

    Step by step

    1. Create count, an int[] of size 26. count[0] counts the A's in the window, count[1] the B's, and so on. C# fills a new int array with zeros.
    2. Declare maxCount as 0. It holds the largest count of one letter seen in the window.
    3. Declare answer and first, both 0. first is the left end of the window and answer is the longest good window so far.
    4. Loop last from 0 to s.Length - 1. Each turn adds the letter at last to the window.
    5. Convert the letter to an index with s[last] - 'A', then add 1 to count[index].
    6. Update maxCount with Math.Max. 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 length is last - first + 1, and subtracting maxCount leaves the characters that would have to change. The loop runs while that is greater than k.
    8. Drop the first letter inside the loop: decrease its count and move first right. maxCount stays as it is.
    9. Record the length with answer = Math.Max(answer, last - first + 1). At this point the window needs at most k changes.
    10. Return answer after the loop.

    The solution in C#

    class Solution {
        public int CharacterReplacement(string s, int k) {
            int[] count = new int[26];
            int maxCount = 0;
            int answer = 0, first = 0;
            for (int last = 0; last < s.Length; last++) {
                int index = s[last] - 'A';
                count[index]++;
                maxCount = Math.Max(maxCount, count[index]);
                while (last - first + 1 - maxCount > k) {
                    count[s[first] - 'A']--;
                    first++;
                }
                answer = Math.Max(answer, last - first + 1);
            }
            return answer;
        }
    }
    

    The C# details worth knowing:

    • Subtracting chars gives an int. s[last] is a char, and 'A' is a char. The - operator converts both to int, so 'C' - 'A' is 2. Because A to Z are consecutive, this maps each letter to 0 through 25.
    • s.Length, not s.Length(). On a string, Length is a property, so it has no parentheses. Code ported from Java or Python often gets this wrong.
    • s[i] is read-only. Strings are immutable in C#, which is fine here: the method never changes s, it only counts letters.
    • count[index]++ works on array elements. It increments the element in place, and count[s[first] - 'A']-- decrements one the same way.
    • Several declarations on one line. int answer = 0, first = 0; declares two int variables, each with its own initial value.

    Complexity

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

    Space: O(1). The count array has 26 entries whatever the length of the string. A string of 100,000 letters uses the same memory for counting as a string of 3.

    Edge cases and common mistakes

    • A single character. "A" with k = 0 returns 1.
    • One repeated letter. "AAAA" with k = 0 returns 4, and a string of 100,000 A's with k = 0 returns 100000.
    • k = 0. The answer is the longest run that already exists. "ABCD" gives 1, "AAAB" gives 3, and "ABAA" gives 2.
    • k as large as the string. "ABCD" with k = 4 returns 4, because every character may change. With k = 1 the same string returns 2.
    • Counting the number to change wrongly. The cost is the window length minus the largest count, not the number of distinct letters.
    • Moving first backwards or resetting it. The window only ever slides to the right. Restarting the left end from 0 after a failure turns the pass into O(n²).
    • Forgetting - 'A'. count[s[last]] would use the character code (65 to 90) as an index, which is outside an array of 26 elements and throws IndexOutOfRangeException.
    • Recomputing maxCount by scanning all 26 counts after every removal is correct but slower by a constant factor. The lazy version is enough.

    Testing

    • "ABAB", k = 2 gives 4.
    • "AABABBA", k = 1 gives 4.
    • "ABBBAABBBBA", k = 2 gives 9.
    • "A", k = 0 gives 1.
    • "ABCD", k = 0 gives 1.
    • "ABCD", k = 1 gives 2.
    • "ABCD", k = 4 gives 4.
    • "AAAB", k = 0 gives 3.
    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