Start learning free

LESSON 447 OF 671 · SLIDING WINDOW

Longest Repeating Character Replacement in JavaScript: O(n) 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

    JAVASCRIPT · SLIDING WINDOW

    Longest Repeating Character Replacement in JavaScript, explained

    Problem overview

    characterReplacement(s, k) 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.

    For s = "AABABBA" and k = 1 the answer is 4. Changing the A at index 3 into a B turns the middle into "BBBB". No single change produces a run of 5.

    The statement asks for 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

    Trying every substring and counting its letters would take O(n²) or worse. A sliding window does it in one pass. The window is the substring from index first to index last, and a small array of counts describes the letters inside it.

    The key question for a window is how many changes it needs. The best plan is to keep its most common letter and change every other character. So:

    changes needed = window length - count of the most common letter

    If that number is at most k, the whole window can become one letter, and its length is a candidate for the answer. If it is bigger than k, the window is too wide, so its left end moves right until it fits again.

    The right end moves forward one character at a time, and the left end only moves right. Each index enters the window once and leaves at most once, which gives the linear time.

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

    lastletter addedfirst after shrinkingmaxCountwindow lengthanswer
    0A0111
    1A0222
    2B0233
    3A0344
    4B1344
    5B2344
    6A3344

    Step by step

    1. Create the counters. new Array(26).fill(0) makes 26 zeros: count[0] counts the A's in the window, count[1] the B's, and so on.
    2. Track maxCount, the largest count of one letter seen in the window.
    3. Declare answer and first, both starting at 0. first is the window's left end.
    4. Loop with last from 0 to s.length - 1. Each turn adds the letter at last to the window.
    5. Convert the letter to a number from 0 to 25. charCodeAt gives the character's code, and the codes of A to Z are consecutive, so subtracting the code of 'A' gives 0 for A, 1 for B and so on. Then increase that count.
    6. Update maxCount. Only the letter just added changed its count, so it is the only one that can beat the current maximum.
    7. Shrink while the window needs too many changes: last - first + 1 - maxCount > k. The first part is the window length.
    8. Drop the first letter by decreasing its count and moving first right.
    9. Update answer with the current window length. At this point the window needs at most k changes.
    10. Return answer.

    The solution in JavaScript

    class Solution {
        characterReplacement(s, k) {
            let count = 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;
        }
    }
    

    The details worth a closer look:

    • charCodeAt returns a number. "B".charCodeAt(0) is 66 and 'A'.charCodeAt(0) is 65, so the difference is 1. Indexing a string like s[last] gives a one-character string, which can't be used as an array position for this purpose.
    • new Array(26).fill(0). new Array(26) alone makes 26 empty slots. fill(0) sets each to 0, so count[index]++ starts from a number. Counting on an undefined slot would give NaN.
    • Several variables in one let. let answer = 0, first = 0; declares both, each with its own initial value.
    • Math.max. It returns the larger of its arguments, which keeps maxCount and answer from ever going down.

    Why maxCount never goes down

    When a letter leaves the window, the code lowers its count but not maxCount. That looks wrong, since maxCount may now be larger than the real largest count in the window. In the table above, at last = 4 the window is "ABAB" (indexes 1 to 4), whose real largest count is 2, while maxCount is still 3.

    It still gives the right answer. The result can only grow when a window longer than the best one so far becomes valid, and that needs a letter whose real count exceeds the old maxCount. When that happens, maxCount is raised for real. In the meantime, a stale value only stops the window from shrinking below the best length already found. So the window never gets smaller once it has reached a given size; it slides along, and answer is the largest size it reached.

    Complexity

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

    Space: O(1). The count array has 26 entries whatever the length of s.

    Edge cases and common mistakes

    • k = 0. No changes are allowed, so the answer is the longest existing run. For "AABABBA" it is 2, and for "ABCDE" it is 1.
    • k as large as the string. Every character can be changed, so the answer is s.length. For "ABCDE" with k = 5 the function returns 5.
    • One character. "A" with k = 0 gives 1.
    • Counting in the wrong direction. The cost is the window length minus the count of the most common letter, not the count itself.
    • Off-by-one in the length. The window from first to last inclusive has last - first + 1 characters.
    • Recomputing the maximum on every shrink. Scanning all 26 counts works too, but it isn't needed, as explained above.
    • Using if instead of while to shrink. With a single step the window can stay invalid, because the one letter that left may not have been enough to bring the changes down to k.

    Testing

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