- Interview Questions
- /
- Problems
- /
- Longest Repeating Character Replacement
Longest Repeating Character Replacement
Find the longest stretch of a string you can turn into one repeated letter by changing at most k characters. A sliding window whose validity depends on its most frequent letter. Solve it below in Python or JavaScript, then read the walkthrough.
Problem
You're given a string s of uppercase English letters and an integer k. You may pick up to k positions in s and change each of those characters to any uppercase letter.
Return the length of the longest substring that can be made of a single repeated letter after at most k changes.
Example 1
- Input
- s = "XYXXZX", k = 1
- Output
- 4
Change the Y at index 1 to get "XXXX" from the first four characters. Changing Z instead also gives a block of four.
Example 2
- Input
- s = "PPQQ", k = 2
- Output
- 4
Change both Qs to P (or both Ps to Q).
Example 3
- Input
- s = "ABCDE", k = 0
- Output
- 1
With no changes allowed, the longest run of one letter is a single character.
Constraints
- 1 ≤ s.length ≤ 10⁵
- s contains only uppercase English letters.
- 0 ≤ k ≤ s.length
Practice
Runs 14 tests in your browser. Python loads on the first run (about 6 MB, then cached). Press ⌘/Ctrl + Enter to run.
Get asked Longest Repeating Character Replacement in a real interview?
Interview Solver gives you a working solution live, during your actual coding interview. Invisible to screensharing.
How to solve Longest Repeating Character Replacement
Pattern: Sliding window with a max-frequency count
For any substring, the cheapest way to make it one letter is to keep its most common letter and change everything else. So a window of length len is fixable exactly when len - maxCount <= k, where maxCount is how often its most frequent letter appears.
That condition is monotone in the right way for a sliding window: grow the right edge one character at a time, and when the window stops being fixable, move the left edge forward. A neat extra trick: you never need to decrease maxCount when the left edge moves. A stale, too-high maxCount can only keep the window at its current size; it can never let the answer grow past a length that was truly achievable, because the answer only grows when a real new maximum appears.
Approach 1: Check every substring
For each start index, extend the end one character at a time while tracking letter counts and the running maximum count. Record the longest window with length - maxCount <= k. With 26 letters this is quadratic, and too slow for long strings.
Time O(n²) · Space O(1)
Approach 2: Binary search on the answer
If a window of length L is fixable, so is some window of every shorter length. Binary search L, and for each candidate slide a fixed window of length L across the string with letter counts, checking the 26 counts at each step.
Time O(26 · n log n) · Space O(1)
Approach 3: Sliding window that never shrinks
- Keep counts for the current window
[left, right]andmaxCount, the highest count seen. - Add
s[right], update its count andmaxCount. - If
(right - left + 1) - maxCount > k, drops[left]from the counts and moveleftforward by one. - The answer is the window length at the end (it only ever grows or holds).
Because each step moves left at most once, the window slides rather than shrinks, and its length is the best answer found so far.
Time O(n) · Space O(1) (26 counters)
| Approach | Time | Space |
|---|---|---|
| Check every substring | O(n²) | O(1) |
| Binary search on the answer | O(26 · n log n) | O(1) |
| Sliding window that never shrinks | O(n) | O(1) (26 counters) |
Solution code
Try the practice editor first. Both solutions pass every test above.
Longest Repeating Character Replacement solution in Python
def character_replacement(s: str, k: int) -> int:
counts = [0] * 26
left = 0
max_count = 0
for right, ch in enumerate(s):
idx = ord(ch) - 65
counts[idx] += 1
max_count = max(max_count, counts[idx])
if right - left + 1 - max_count > k:
counts[ord(s[left]) - 65] -= 1
left += 1
return len(s) - leftLongest Repeating Character Replacement solution in JavaScript
function characterReplacement(s, k) {
const counts = new Array(26).fill(0);
let left = 0;
let maxCount = 0;
for (let right = 0; right < s.length; right++) {
const idx = s.charCodeAt(right) - 65;
counts[idx]++;
maxCount = Math.max(maxCount, counts[idx]);
if (right - left + 1 - maxCount > k) {
counts[s.charCodeAt(left) - 65]--;
left++;
}
}
return s.length - left;
}Common mistakes
- Treating the stale maxCount as the true maximum of the current window. It is only used to decide whether the window may grow, not to describe the window.
- Counting the number of distinct letters instead of using the most frequent letter.
- Using a while loop to shrink the window and then recomputing maxCount downward, which is correct but more code than needed and easy to get wrong.
- Forgetting the k = 0 case, where the answer is the longest existing run.
What interviewers look for
Start from the fixability test: "keep the most common letter, change the rest, so the window is valid when length minus max count is at most k." Once that's on the board, the sliding window follows.
The stale maxCount trick is the part interviewers like to probe. If you use it, be ready to explain why it's safe. If you're not confident, recompute the max from the 26 counts each step: it's still linear and much easier to defend.
Follow-up questions
What if the string can contain any Unicode character?
Use a hash map for counts. With the never-shrinking window you never need to recompute the maximum, so each step stays O(1) on average no matter how large the alphabet is.
How would you also return which substring it is?
Record left and right whenever the window length reaches a new maximum. The substring s[left..right] at that moment is a valid answer, using its most frequent letter as the target.
What if the string is binary and you may flip at most k zeros to ones?
That is Max Consecutive Ones III: the same sliding window, but the condition is simply "number of zeros in the window <= k". It is the special case where the target letter is fixed.
Companies that ask Longest Repeating Character Replacement
Longest Repeating Character Replacement is tagged by 102 companies in our interview dataset. The score shows how often it comes up at each company.
- Amrock100%
- Astronomer100%
- Pocket Gems100%
- Cred100%
- Avaya97%
- Apptio96%
- Xilinx95%
- Postman94%
- Shipt93%
- John Deere92%
- Gemini91%
- Cabaletta Bio91%
- Epic Games89%
- Knowbe487%
- Farfetch86%
- Think Surgical84%
- Eventbrite83%
- Project4482%
- Neogen81%
- Doximity80%
- Alcon79%
- Motorola Solutions78%
- Tableau Software78%
- Trellix77%
and 78 more.
Practice next
- Longest Substring Without Repeating CharactersMediumSliding window with last-seen index
- Minimum Window SubstringHardVariable-size sliding window with counts
- Maximum Number of Occurrences of a SubstringMediumFixed-size sliding window with a frequency map
- Group AnagramsMediumHash map keyed by a canonical form
Get live help in the real interview
Working solutions in real time during your actual interview. Invisible to screensharing.
Start Free TrialNo credit card required