InterviewPrepKit

Home / Coding / Sliding Window

Longest Repeating Character Replacement

medium Original β†—
Solving tips
  • Key validity test: a window is fixable when window_len - count_of_most_frequent_letter <= k, so you only replace the non-majority characters.
  • Since validity is monotone, use a variable-size window: grow right unconditionally, shrink left while invalid, and record the max size.
  • Optimization: track a stale max_freq that never decreases and slide (if not while), giving true O(n) instead of O(26*n) and never shrinking the window.
  • Common pitfall: the formula is window_len - max_freq <= k (not max_freq <= k), and record best only when the window is valid.

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 = 2 β†’ 4 β€” change both As (or both Bs) and the whole string becomes one letter.
  • s = "AABABBA", k = 1 β†’ 4 β€” change the middle B in "AABA" to get "AAAA" (window indices 0–3; "ABBA" β†’ "BBBB" also works).
  • s = "AAAA", k = 0 β†’ 4 β€” already uniform; zero replacements needed.

Constraints

  • 1 <= len(s) <= 10^5
  • s contains only uppercase English letters (A–Z, 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.)
Your workspace Not runnable by design β€” this is your interview scratchpad. Saved on this device.