Longest Repeating Character Replacement
On this page
Problem statement
Given a string of uppercase letters and an integer k, you may change at most k characters to any other uppercase letter. Return the length of the longest substring that can be made of a single repeated letter.
A sliding window problem with one clever observation: a window is fixable exactly when its length minus the count of its most common letter is at most k. Variants change the alphabet or ask for the longest run of 1s with k flips, and the same window answers them all. Original problem: LeetCode 424.
Example

s = "ABBACBB", k = 2
Output: 6 # "BBACBB" -> change A and C -> "BBBBBB"
s = "ABBACBB", k = 1
Output: 3 # e.g. "ABB" -> "BBB"
Constraints (assumed)
- 1 ≤ n ≤ 10⁵; uppercase English letters; 0 ≤ k ≤ n.
What this question tests
- Turning "can this substring be fixed?" into a window condition:
length − maxFreq ≤ k. - A clean grow-right, shrink-left window with letter counts.
- Understanding why maxFreq doesn't have to decrease when the window shrinks.
Questions to ask first
- Which characters can appear? (Here: 26 uppercase letters, so a fixed-size count array works.)
- Must I use all k changes? (No; at most k.)
- Can k be 0 or at least n? Then the answer is the longest existing run, or n.
- Do you want the substring or its length? (Here: the length.)
Try it yourself first
You have the full problem. Sketch your answer, then sign up free to read the complete walkthrough.
- The complete design, flow by flow, with pictures
- Deep dives into the hard parts
- What mid, senior and staff candidates are expected to say
- Full company question lists
Free forever. No card needed.