Algo-Sim › Sliding Window

Longest Repeating Character Replacement

Medium · Sliding Window · step through it in Java, Python and C++ on your own input

Replace at most k characters of s; return the length of the longest substring of one repeated letter you can get.

Problem

You are given a string s of uppercase letters and an integer k. You may change any character into any other uppercase letter, at most k times in total. Return the length of the longest substring that consists of a single repeated letter after those changes.

Constraints

Edge cases to test

Follow-up questions

Why is it fine not to lower maxCount when the window shrinks?
A stale maxCount only keeps the window from shrinking; it can grow only when a real count beats the old best, which is the only way to improve the answer.
What if the alphabet is large?
Use a hash map of counts instead of 26 slots: still O(n) time, O(alphabet) space.

Solution

Java

public int characterReplacement(String s, int k) {
    int[] count = new int[26];
    int left = 0, maxFreq = 0, best = 0;
    for (int right = 0; right < s.length(); right++) {
        int c = s.charAt(right) - 'A';
        maxFreq = Math.max(maxFreq, ++count[c]);
        while (right - left + 1 - maxFreq > k) {
            count[s.charAt(left) - 'A']--;
            left++;
        }
        best = Math.max(best, right - left + 1);
    }
    return best;
}

Python

def character_replacement(s, k):
    count = [0] * 26
    left = max_freq = best = 0
    for right in range(len(s)):
        c = ord(s[right]) - 65
        count[c] += 1
        max_freq = max(max_freq, count[c])
        while right - left + 1 - max_freq > k:
            count[ord(s[left]) - 65] -= 1
            left += 1
        best = max(best, right - left + 1)
    return best

C++

#include <bits/stdc++.h>
using namespace std;

class Solution {
  public:
    int characterReplacement(string &s, int k) {
        vector<int> count = vector<int>(26);
        int left = 0, maxFreq = 0, best = 0;
        for (int right = 0; right < int(s.size()); right++) {
            int c = s[right] - 'A';
            maxFreq = std::max(maxFreq, ++count[c]);
            while (right - left + 1 - maxFreq > k) {
                count[s[left] - 'A']--;
                left++;
            }
            best = std::max(best, right - left + 1);
        }
        return best;
    }
};

More Sliding Window problems