Longest Repeating Character Replacement

Find the longest run of one repeated letter you can make by changing at most k letters.

Given a string s of uppercase English letters and a number k, you may change any letter of s into any other uppercase letter, at most k times in total. Return the length of the longest substring, a run of neighbouring letters, that can be made of one repeated letter.

Example 1
Input: s = "ABAB", k = 2
Output: 4
Explanation: change both A's to B's, or both B's to A's.
Example 2
Input: s = "AABABBA", k = 1
Output: 4
Explanation: change the middle A to B to get "AABBBBA", which contains "BBBB".
Solution

The Idea

Picture the letters of s as a row of tiles, and imagine you may repaint up to k of them with any letter you like. The question is how long a run of matching tiles you can end up with.

Take Example 2, AABABBA with k = 1, and pick a stretch of neighbouring letters, say AABA. To turn it into one repeated letter, keep the letter it has most of, A, and change the rest, here the single B. That is one change, and k = 1 allows it. So a stretch needs as many changes as it has letters, minus the count of its most common letter.

Look at the picture below, where each row is one stretch, outlined in blue, and the letters to change are orange.

Three stretches of AABABBA with k = 1. AABA has 4 letters and 3 A's, so 1 change: it fits. AABAB has 5 letters and 3 A's, so 2 changes: too many. BABB has 4 letters and 3 B's, so 1 change: it fits.

The row labelled AABA has 4 letters and 3 A's, so it needs 1 change and fits. The row labelled AABAB adds the B at index 4: 5 letters, still 3 A's, so 2 changes, which is too many. The row labelled BABB starts at index 2 and has 3 B's, so it fits with 1 change. Changing its A gives BBBB, the answer of Example 2.

A string of 7 letters has 28 stretches, and one of 10,000 letters has about 50 million. Do we have to check them all? Look again at AABAB. Adding a letter to a stretch adds one to its length but at most one to the count of its most common letter, so the changes it needs never go down. Every longer stretch that starts at index 0 therefore needs at least 2 changes too.

So once a stretch needs too many changes, growing it further is pointless, and its start should move right instead. One stretch is then enough: its right end takes in one new letter at a time, and its left end moves forward only when the stretch needs more than k changes. A stretch handled this way is called a window, and moving both ends forward like this is the sliding window technique.

Solution Approach

Turning that idea into code means settling three things: how to count the changes a window needs, how far the left end moves when the window needs too many, and how to know the count of the most common letter as letters leave.

Counting the changes in a window

How do we know how many changes the window needs? The simple way checks every stretch on its own, with one loop for the start and one for the end, which means about n²/2 stretches for n letters. The window needs less work: it keeps an array of 26 counts, one per letter, and changes one count by one whenever a letter enters or leaves. The changes it needs are its length minus its highest count.

Moving the left end

When the window needs too many changes, how far should its left end move? One way is to keep removing letters on the left until the window fits again. But removing a single letter is enough, because we only care about a window longer than the best one so far.

Each step adds one letter on the right. If the window then needs too many changes, removing one letter on the left brings it back to its old length, the longest found so far. A shorter window could never beat that, so there is no reason to shrink further. The window slides one place right, keeping its size, and grows only when a window one letter longer fits.

A window that has slid may itself need too many changes. In Example 2, the window ends as ABBA, at indexes 3 to 6, which needs 2 changes with k = 1. That does no harm, because the answer is the window's length, not its letters, and a window of that length that fits, AABA, was seen earlier.

Keeping the highest count

When letters leave the window, the highest count inside it can drop. Finding it again would mean scanning all 26 counts. Instead, the code keeps maxCount, the highest count of one letter seen in any window so far, and never lowers it. Why is that safe?

The window only slides once its length has reached maxCount + k, and then a window one letter longer fits only if one letter appears maxCount + 1 times in it. So only a new highest count can make the window grow, and that count comes straight from the letter just added, so it is real. A maxCount that is too high for the current window just keeps it sliding at the best size, which loses nothing.

Java Solution

The method characterReplacement works in these steps:

  1. First, create count, an array of 26 numbers, one per letter. s.charAt(i) - 'A' turns a letter into its place in the array, 0 for A up to 25 for Z. Set left, maxCount and best to 0.
  2. A loop moves right over s, one letter at a time. The new letter's count goes up by one, and maxCount becomes the larger of itself and that count.
  3. The window is s[left..right], which has right - left + 1 letters. If that length minus maxCount is more than k, the letter at left leaves: its count drops by one and left moves one place right.
  4. Keep the longest window length in best, and return it when the loop is done.

The main method runs both examples, ABAB with no changes allowed, ABC with more changes than letters, AAAA that needs no changes, and ABBBACCCCD, where the longest run comes from a letter that shows up late.

Java
public class LongestRepeatingCharacterReplacement {

    public static int characterReplacement(String s, int k) {
        int[] count = new int[26];
        int left = 0;
        int maxCount = 0;                     // highest count of one letter seen in a window
        int best = 0;
        for (int right = 0; right < s.length(); right++) {
            maxCount = Math.max(maxCount, ++count[s.charAt(right) - 'A']);
            // letters to replace = window size - most common letter
            if (right - left + 1 - maxCount > k) {
                count[s.charAt(left) - 'A']--;
                left++;                       // slide the window instead of growing it
            }
            best = Math.max(best, right - left + 1);
        }
        return best;
    }

    static void show(String s, int k) {
        System.out.println(s + ", k = " + k + ": " + characterReplacement(s, k));
    }

    public static void main(String[] args) {
        show("ABAB", 2);
        show("AABABBA", 1);
        show("ABAB", 0);
        show("ABC", 5);
        show("AAAA", 0);
        show("ABBBACCCCD", 1);
    }
}

Running it prints:

Output
ABAB, k = 2: 4
AABABBA, k = 1: 4
ABAB, k = 0: 1
ABC, k = 5: 3
AAAA, k = 0: 4
ABBBACCCCD, k = 1: 5

With k = 0, ABAB prints 1, since no two neighbouring letters are equal. ABC with k = 5 prints 3: changes to spare cannot make the run longer than the string. The window length is right - left + 1; writing right - left in the if check instead allows one change too many, and the ABAB, k = 0 line then prints 3.

Look at the last line, ABBBACCCCD with k = 1. The three B's set maxCount to 3, and the window grows to ABBB. It then slides through BBBA, BBAC, BACC and ACCC at length 4, even though BBAC needs 2 changes. At index 8 the fourth C raises maxCount to 4, and the window grows to ACCCC, 5 letters with 1 change, which gives the 5.

The original implementation, LongestRepeatingCharacterReplacement.java, is on GitHub.

Complexity

The work is one pass of the window's right end over s, with a fixed amount of work for each letter.

  • Time: O(n), because right visits each of the n letters once, left only moves forward, and each step changes at most two counts and compares a few numbers.
  • Space: O(1), because the count array always has 26 entries, one per uppercase letter, however long s is.

For an array of ones and zeros, the same idea is Max Consecutive Ones III, where the values to change are the zeros.