InterviewPrepKit

Home / Coding / Algorithm & Data Structure / Sliding Window

Longest Repeating Character Replacement

medium Original ↗ 00:00

Problem

You are given a string s of uppercase English letters and an integer k. You may change at most k characters of s to any other uppercase letters. Return the length of the longest substring consisting of a single repeated letter that you can produce this way.

Equivalently: find the longest window of s that can be made uniform by rewriting at most k of its characters.

Examples

  • s = "ABAB", k = 24 — change both As (or both Bs) and the whole string becomes one letter.
  • s = "AABABBA", k = 14 — change the middle B in "AABA" to get "AAAA" (window indices 0–3; "ABBA" → "BBBB" also works).
  • s = "AAAA", k = 04 — already uniform; zero replacements needed.

Constraints

  • 1 <= len(s) <= 10^5
  • s contains only uppercase English letters (AZ, so at most 26 distinct).
  • 0 <= k <= len(s)

Checking all O(n²) windows is too slow at n = 10^5; the expected solution is O(n) (or O(26·n)).

Think about it first

Hint 1 For a fixed window, which characters should you replace? Everything except the most frequent letter. The window is fixable iff window_length - count_of_most_frequent_letter <= k.
Hint 2 As the window grows rightward it can only get harder to fix, and shrinking from the left can only help. That monotonicity means two pointers that never move backward suffice.
Hint 3 Keep letter counts in the window. Extend right each step; while (right - left + 1) - max(counts) > k, decrement counts at s[left] and advance left. The answer is the largest valid window seen. (Bonus: you never need to shrink below the best size — a stale max frequency still yields the right answer.)

Write your solution, then hit Run tests to check it — or get a mock grade from the AI coach.

The coach remembers this session — revise your code and ask again, and it grades your progress. It gives hints, not the answer.
Report a bug