Start learning free

LESSON 166 OF 314 · SLIDING WINDOW

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

    JAVA · SLIDING WINDOW

    Longest Repeating Character Replacement in Java, explained

    Problem overview

    The method characterReplacement receives a string s of uppercase letters and an integer k. You may change up to k characters of s into any other uppercase letters. It returns the length of the longest substring that can be made of a single repeated letter this way.

    For s = "AABABBA" and k = 1, changing the A at index 3 into a B gives AABBBBA, which contains BBBB, so the answer is 4. For s = "ABBBAABBBBA" and k = 2, changing the two As at indexes 4 and 5 turns indexes 1 to 9 into nine Bs, so the answer is 9.

    Approach: a window that needs at most k changes

    Look at one substring. To turn it into a single repeated letter with as few changes as possible, keep its most common letter and change every other letter. The cost is therefore:

    window length - count of the most common letter in it

    A substring is a valid answer exactly when that cost is at most k. So the task becomes: find the longest window whose length minus its largest letter count is at most k.

    That suits a sliding window. The right end last moves forward one letter at a time and adds that letter to the window. When the window has become too expensive, the left end first moves forward to shrink it. Both ends only move right, so the work is O(n). Trying every substring and counting its letters would be O(n squared) or worse.

    A table of 26 counts, one per letter, describes the window's contents. It has a fixed size, so the extra space is O(1).

    Step by step

    1. Create count, an int[26]. Index 0 counts the As in the window, index 1 the Bs, and so on. Java fills a new int array with zeros.
    2. Declare maxCount, the largest count of one letter in the window, starting at 0.
    3. Declare answer and first as 0. first is the window's left end and answer is the longest valid window so far.
    4. Loop last from 0 to s.length() - 1. Each turn adds the letter at last to the window.
    5. Find the letter's slot. s.charAt(last) - 'A' is 0 for A, 1 for B and so on. A char is a number in Java and the letters are consecutive, so the subtraction gives an int. 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 set a new maximum.
    7. Shrink while the window is too expensive: last - first + 1 - maxCount > k. The first part is the window length, so the whole expression is the number of letters you would have to change.
    8. Drop the leftmost letter by decreasing its count and moving first right by one.
    9. Record the length. After the shrinking, the window needs at most k changes, so answer becomes the larger of itself and last - first + 1.
    10. Return answer.

    The solution in Java

    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.charAt(last) - 'A';
                count[index]++;
                maxCount = Math.max(maxCount, count[index]);
                while (last - first + 1 - maxCount > k) {
                    count[s.charAt(first) - 'A']--;
                    first++;
                }
                answer = Math.max(answer, last - first + 1);
            }
            return answer;
        }
    }
    

    Details worth understanding:

    • Why maxCount is never lowered. When a letter leaves the window, maxCount may be larger than the real maximum. That stale value can make the window look cheaper than it is, so the window may stay at a size that is not valid. That is harmless: such a window is no longer than the best one already recorded in answer, so it cannot raise the answer. A longer window can only count as valid after some letter reaches a count above the stale maxCount, and then maxCount is raised for real. Keeping the old value saves a scan of the 26 counts at every step.
    • char arithmetic. In s.charAt(last) - 'A' both operands are promoted to int, so the result is an int that can index an array directly. This only works because the input contains uppercase letters; any other character would give an index outside 0 to 25 and throw ArrayIndexOutOfBoundsException.
    • s.length() is a method on String, while .length without parentheses is the field of an array.

    Complexity

    Time: O(n). last visits each index once, and first only moves right, so the while loop's body runs at most n times over the whole call.

    Space: O(1). The 26-slot array and a few integers don't depend on 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. "AAAA" gives 4, "ABCD" gives 1 and "AABA" gives 2.
    • k as large as the string. Every letter can be changed, so the answer is the whole length: "ABCD" with k = 4 gives 4.
    • A single letter. "A" with k = 0 gives 1.
    • Counting the cost as maxCount alone. The test is length - maxCount against k, not maxCount against k.
    • Off-by-one in the length. A window from first to last, both included, holds last - first + 1 letters.
    • Forgetting to decrease the count of the letter that leaves. The counts then describe letters that are no longer in the window.

    Testing

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