Start learning free

LESSON 166 OF 314 · SLIDING WINDOW

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

    TYPESCRIPT · SLIDING WINDOW

    Longest Repeating Character Replacement in TypeScript, 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, each into any uppercase letter. The method returns the length of the longest substring made of one 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". Changing the B at index 2 gives "AAAA" instead. No single change gives a run of 5.

    Approach

    Instead of trying every change, look at windows: substrings from index first to index last. A window can become one repeated letter if the number of characters that are not its most common letter is at most k. The best plan for a window is to keep its most common letter and change all the others, so the condition is:

    window length - count of the most common letter <= k

    Checking every window with its own count would cost O(n²) or worse. A sliding window does it in one pass: the right end last moves forward one letter at a time, and whenever the window needs more than k changes, the left end first moves forward until it is valid again. Both ends only move right, so the work is O(n). Because the letters are only A to Z, the counts fit in an array of 26 numbers, which is O(1) space.

    Step by step

    1. Count the letters in the window. count has 26 zeros: count[0] is the number of A's in the window, count[1] the number of B's, and so on.
    2. Remember the largest count. maxCount starts at 0 and holds the highest count of one letter seen in the window.
    3. Set up the window and the answer. first is the window's left end and answer the longest valid window found so far. Both start at 0.
    4. Grow the window. A for loop moves last over every index of s, adding one letter per turn.
    5. Turn the letter into an index. s.charCodeAt(last) is the character's code. The codes of A to Z are consecutive, so subtracting the code of 'A' gives 0 for A, 1 for B and so on. Add one to that count.
    6. Update maxCount. Only the letter just added changed, so it is the only one that can beat the old maximum: Math.max(maxCount, count[index]).
    7. Shrink while the window needs too many changes. last - first + 1 is the window's length. Subtract maxCount, the letters kept, and what is left is the number of letters to change. While that is more than k, the window is invalid.
    8. Drop the first letter. Inside the while, lower the count of the letter at first and move first right by one.
    9. Record the length. Once the window needs at most k changes, all of it can become one letter, so answer becomes the larger of itself and last - first + 1.
    10. Return answer.

    The solution in TypeScript

    class Solution {
        characterReplacement(s: string, k: number): number {
            let count: number[] = new Array(26).fill(0);
            let maxCount = 0;
            let answer = 0, first = 0;
            for (let last = 0; last < s.length; last++) {
                let index = s.charCodeAt(last) - 'A'.charCodeAt(0);
                count[index]++;
                maxCount = Math.max(maxCount, count[index]);
                while (last - first + 1 - maxCount > k) {
                    count[s.charCodeAt(first) - 'A'.charCodeAt(0)]--;
                    first++;
                }
                answer = Math.max(answer, last - first + 1);
            }
            return answer;
        }
    }
    

    Details worth knowing:

    • Characters have no numeric value of their own. A string's character is another string, so subtracting 'A' from it does not give a letter number. Use charCodeAt: "B".charCodeAt(0) - "A".charCodeAt(0) is 1. Using it on "Z" gives 25, the last slot of count.
    • new Array(26).fill(0) creates 26 slots and fills each with 0. Without fill, the slots would be empty and count[index]++ would produce NaN.
    • Counts are plain numbers. They are doubles, but with strings of at most 100,000 characters every count stays far below the size where whole numbers stop being exact.

    Why maxCount is never lowered

    When a letter leaves the window, maxCount is not recomputed, so it can be larger than the real maximum of the current window. This does no harm. The window only fails to shrink in those moments, so its length never drops below the best length found so far, and answer only grows. A longer valid window needs a letter whose count really is bigger, and that raises maxCount for real. Recomputing the maximum from the 26 counts each time would also work, but costs more for no gain.

    Walking through an example

    For s = "AABABBA" and k = 1, each turn of the loop ends with this window:

    lastletterwindowmaxCountanswer
    0A"A"11
    1A"AA"22
    2B"AAB"23
    3A"AABA"34
    4B"ABAB"34
    5B"BABB"34
    6A"ABBA"34

    At last = 4 the window "AABAB" has length 5 and a largest count of 3, so it needs 2 changes. That is more than k = 1, so first moves once. From then on the window keeps its length of 4 while sliding right.

    Complexity

    Time: O(n). last visits each index once, and first only moves right, so the while body runs at most n times over the whole call. Space: O(1). The array has 26 slots no matter how long s is.

    Edge cases and common mistakes

    • k = 0. No change is allowed, so the answer is the longest run of one letter already in s: "ABAB" with k = 0 gives 1, and "AAAA" gives 4.
    • k at least the length of s. Everything can be changed, so the window never shrinks and the answer is s.length: "ABCDE" with k = 5 gives 5.
    • A single letter. "A" with k = 0 gives 1.
    • Forgetting the + 1 in the length. A window from first to last inclusive has last - first + 1 letters.
    • Checking the wrong letter. The best letter to keep is the most common one in the window, not the letter at the right end.

    Testing

    skResult
    "ABAB"24
    "AABABBA"14
    "ABBBAABBBBA"29
    "A"01
    "ABCDE"01
    "ABCDE"55
    "AAAA"04
    "ABAB"01
    Keep going with TypeScript1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free