Longest Repeating Character Replacement

Find the longest substring that can be turned into one repeated letter with at most k changes, using a sliding window and the count of its most common letter.

Time O(n)Space O(1)Code C#
Watch it animatedStep through it, with the running line highlighted. Free with an account.

The idea

To turn a window into one repeated letter, keep every copy of its most common letter and change all the others: that costs length − maxFreq changes. So the window is valid while length − maxFreq <= k. Grow on the right; when the window needs too many changes, drop one letter from the left. maxFreq is the highest count ever seen and is never lowered: the answer can only grow when some letter reaches a new, higher count.

Code

public static int CharacterReplacement(string s, int k) {
    var count = new int[26];
    int left = 0, maxFreq = 0, best = 0;
    for (int right = 0; right < s.Length; right++) {
        maxFreq = Math.Max(maxFreq, ++count[s[right] - 'A']);
        while (right - left + 1 - maxFreq > k) {
            count[s[left] - 'A']--;
            left++;
        }
        best = Math.Max(best, right - left + 1);
    }
    return best;
}

Tips

In the .NET library

s[right] - 'A' turns a char into an index 0..25 without any lookup. ++count[...] inside Math.Max increments first and passes the new value.