Skip to content
DSA Patterns
Menu
Language
Sliding WindowLC #4244 of 6← PreviousNext →

Demo preview: These solutions pass the automated test suite but have not been human-reviewed. Treat trade-offs and prose as draft.

Longest Repeating Character Replacement

Problem (restated)

You may replace at most k characters in string s. Return the length of the longest substring that can be made all the same character.

Intuition

In a window, replacements needed = window length, count of the most frequent character. Keep that ≤ k.

Approaches

Sliding window + max frequency

Unverified
Time O(n)Space O(1)

Idea. Expand right, track char counts and maxFreq in window. While (right-left+1, maxFreq) > k, shrink left.

Walkthrough. s=“AABABBA”, k=1. Window can hold “AABA” (1 replace) length 4; “ABABB” shrinks; best stays 4.

Trade-offs. maxFreq need not decrease when shrinking for correctness of the answer (window never needs to shrink below historical max).

Solution
export function characterReplacement(s: string, k: number): number {
  const cnt = new Array<number>(26).fill(0);
  let left = 0, maxFreq = 0, best = 0;
  for (let right = 0; right < s.length; right++) {
    const i = s.charCodeAt(right)! - 65;
    cnt[i]!++;
    maxFreq = Math.max(maxFreq, cnt[i]!);
    while (right - left + 1 - maxFreq > k) {
      cnt[s.charCodeAt(left)! - 65]!--;
      left++;
    }
    best = Math.max(best, right - left + 1);
  }
  return best;
}
export function characterReplacement(s: string, k: number): number {
  const cnt = new Array<number>(26).fill(0);
  let left = 0, maxFreq = 0, best = 0;
  for (let right = 0; right < s.length; right++) {
    const i = s.charCodeAt(right)! - 65;
    cnt[i]!++;
    maxFreq = Math.max(maxFreq, cnt[i]!);
    while (right - left + 1 - maxFreq > k) {
      cnt[s.charCodeAt(left)! - 65]!--;
      left++;
    }
    best = Math.max(best, right - left + 1);
  }
  return best;
}

Template connection

Max window under a replacement budget. maxFreq is the highest count inside the window. While length - maxFreq > k, move the left edge. maxFreq does not have to fall on that shrink; the longest valid window is still the answer.

Reflection

  • The invariant is window length minus the most frequent count, at most k. Do you refresh that count when the character leaves?
  • k = 0 is the longest run of one character. k = n is n.
  • If you only raise maxFreq and never recompute it on a shrink, why is the longest answer still right?
Contributor review checklist

Interactive

Mental model

A worked animation for this problem. Scrub steps or press space to pause; re-tell the invariant out loud.

Step 1 of 6
1/6

Replace at most k=1 letters. Need the longest window with window − maxFreq ≤ 1.

A
0
A
1
B
2
A
3
B
4
B
5
A
6

k = 1

Key:CurrentActive rangeSettled