Longest Repeating Character Replacement

Longest substring achievable with at most k character replacements via a sliding window over character counts.

Medium
Time O(n) Space O(1)
LeetCode
4 min read
sliding-window string

Problem#

Given a string s and an integer k, return the length of the longest substring you can make all-equal by replacing at most k characters.

Examples#

  • s = "ABAB", k = 24
  • s = "AABABBA", k = 14

Constraints#

  • 1 <= s.length <= 10^5, uppercase, 0 <= k <= s.length.

Hints#

Hint 1
A window is valid iff (window length − max count in window) ≤ k. Slide right; only shrink when violated.

Approach#

Sliding window with frequency table. Track maxCount = highest single-character count in the window. The window is valid when length - maxCount ≤ k. When invalid, shift left. We don’t need to recompute maxCount when shrinking because the answer is monotonic in maxCount — keeping a stale max only ever causes us to miss a smaller answer, never a larger one.

Solution#

Longest Repeating Character Replacement
class Solution {
public:
int characterReplacement(string s, int k) {
int count[26] = {0};
int left = 0, maxCount = 0, best = 0;
for (int right = 0; right < (int)s.size(); ++right) {
maxCount = max(maxCount, ++count[s[right] - 'A']);
if (right - left + 1 - maxCount > k) {
--count[s[left] - 'A'];
++left;
}
best = max(best, right - left + 1);
}
return best;
}
};

Editorial#

The crucial insight is that maxCount need not be recomputed on shrink — the answer is monotonic. We never grow the window past a length that exceeds maxCount + k; if maxCount is stale-high, we’d accept a window that would be valid for some hypothetical letter, but the recorded length is still bounded by right - left + 1, which is the best we’ve ever seen. The window’s “left” pointer effectively only ever advances by one per outer step.

Complexity#

  • Time: O(n).
  • Space: O(1) (26 letters).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.