Longest Repeating Character Replacement

Find the longest substring with at most k character replacements.

Pattern

Variable Window + Count

This problem follows the Variable Window + Count pattern, commonly found in the Sliding Window category. Recognizing this pattern is key to solving it efficiently in an interview setting.

Approach

How to Solve It

Window size - max frequency char count <= k means window is valid.

Key Insight

You don't need to decrease maxFreq when shrinking — if it's wrong, the window just won't grow, but it can never give a wrong answer.

Step-by-step

  1. 1Use a sliding window with a frequency map
  2. 2Track the count of the most frequent character in the window
  3. 3If windowSize - maxFreq > k, the window is invalid — shrink from left
  4. 4Update the result with the current window size

Pseudocode

count = {}
left = 0
maxFreq = 0
result = 0
for right in range(len(s)):
    count[s[right]] = count.get(s[right], 0) + 1
    maxFreq = max(maxFreq, count[s[right]])
    if (right - left + 1) - maxFreq > k:
        count[s[left]] -= 1
        left += 1
    result = max(result, right - left + 1)
return result
Complexity Analysis

Time Complexity

O(n)

Space Complexity

O(1)
More Sliding Window Problems

Master this pattern with YeetCode

Practice Longest Repeating Character Replacement and similar Sliding Window problems with flashcards. Build pattern recognition through active recall.

Practice this problem