Skip to problem
←

Longest Repeating Character Replacement

Medium 0 attempts

You're given a string s made of uppercase English letters and a budget of k character replacements — each replacement lets you pick any character in the string and replace it with a different uppercase letter. Using at most k such replacements, find the longest substring you can create that consists of a single repeated letter.

Return the length, not the modified string. The substring must be contiguous; characters cannot be rearranged or skipped. You may use fewer than k replacements. For "AABABBA" with k = 1, changing the B in the first four characters produces "AAAA", giving length 4.

Function contract

Implement characterReplacement(s, k). Receive an uppercase English string and a nonnegative replacement budget.

Output: Return the maximum length of a contiguous substring that can be made uniform using at most k replacements.

Example 1

Input
s = "ABAB"
k = 2
Output
4

Example 2

Input
s = "AABABBA"
k = 1
Output
4
Constraints
  • 1 <= s.length <= 10^5
  • s consists of uppercase English letters
  • 0 <= k <= s.length

Use a sliding window approach. Maintain a count of characters in the current window. If the window size minus the largest character frequency seen so far exceeds k, shrink the window from the left.

maxFreq is a historical maximum, not necessarily the current window's maximum after shrinking. This is safe when finding only the best length: a stale count can retain a window of an already achievable size, but cannot establish a larger record until a sufficiently large frequency is reached again. Do not use this window directly to return the actual substring without validating its current counts.

javascript
function characterReplacement(s, k) {
  const count = {};
  let left = 0, maxFreq = 0, result = 0;

  for (let right = 0; right < s.length; right++) {
    count[s[right]] = (count[s[right]] || 0) + 1;
    maxFreq = Math.max(maxFreq, count[s[right]]);

    while ((right - left + 1) - maxFreq > k) {
      count[s[left]]--;
      left++;
    }

    result = Math.max(result, right - left + 1);
  }

  return result;
}

Time: O(n) Space: O(1) — at most 26 character counts

Loading discussion…

Saved in this browser only. Private to you.

JavaScript