Longest Repeating Character Replacement, explained

Longest Repeating Character Replacement is solved with a sliding window: grow the window to the right, track how often its most common letter appears, and slide the left edge forward whenever the window holds more than k letters that would need changing. One pass gives the answer in O(n) time with a small count table.

By Published 8 min read

The problem in plain words

You are given a string of capital letters and a whole number k. You may pick up to k positions and overwrite each with any letter you like. After those edits, look for the longest contiguous stretch where every letter is the same. Return the length of the best stretch you can create. You do not have to spend the whole budget.

Examples made up for this page, checked by running the code below
StringkAnswerOne way to get it
MMRMQ14Change the R to M, giving MMMM followed by Q
PQPQQP02No edits allowed, so the best is the QQ already there
PQPQQP25Change the two P letters in PQPQQ to Q
ZZZ23Already uniform; the spare edits cannot make it longer
RSTU12Any two neighbors, with one of them rewritten
Examples made up for this page, checked by running the code below. Scroll sideways on a small screen.

Questions to settle first: is the alphabet only capital letters (it usually is, which keeps the count table at 26 slots), can k be zero, and can k exceed the string length? If k is at least the length, the answer is the whole string, and the general code already returns that.

The one fact that unlocks it

Take any window. The cheapest way to make it uniform is to keep its most common letter and overwrite everything else. So the number of edits a window needs is its length minus the count of its most frequent letter. The window is fixable when that number is k or less. Once you see that, the question becomes a search for the longest window that passes the test, which is exactly what a sliding window does well.

Brute force: every start, every end

Fix a start position, then extend the end one letter at a time while keeping a count table and the best count seen in this window. Each time the window passes the test, record its length. That avoids recounting from scratch, but there are still about n²/2 windows, so the cost is O(n²). It is worth saying out loud because it states the test cleanly, and the faster version is the same test applied with less repeated work.

def longest_after_changes_slow(s, k):
    best = 0
    for start in range(len(s)):
        counts = {}
        top = 0
        for end in range(start, len(s)):
            counts[s[end]] = counts.get(s[end], 0) + 1
            top = max(top, counts[s[end]])
            if (end - start + 1) - top <= k:
                best = max(best, end - start + 1)
    return best
Brute force with a running count per start position. O(n²) time.

The sliding window

Keep two indexes, left and right. Move right forward one letter at a time and add that letter to the counts. Keep top, the largest single-letter count you have seen. If the window now needs more than k edits, move left forward by one and remove the letter it leaves. Notice that left moves at most one step per step of right, so the window length never drops. It either grows by one or stays the same size and slides.

def longest_after_changes(s, k):
    counts = {}
    left = 0
    top = 0  # highest count of one letter seen in any window so far
    for right, ch in enumerate(s):
        counts[ch] = counts.get(ch, 0) + 1
        top = max(top, counts[ch])
        # letters that would need changing = window length - top
        if (right - left + 1) - top > k:
            counts[s[left]] -= 1
            left += 1
    return len(s) - left
Python: one pass, O(n) time, count table bounded by the alphabet size.
function longestAfterChanges(s, k) {
  const counts = new Map();
  let left = 0;
  let top = 0;
  for (let right = 0; right < s.length; right++) {
    const ch = s[right];
    counts.set(ch, (counts.get(ch) || 0) + 1);
    top = Math.max(top, counts.get(ch));
    if (right - left + 1 - top > k) {
      counts.set(s[left], counts.get(s[left]) - 1);
      left++;
    }
  }
  return s.length - left;
}
JavaScript: the same window with a Map for counts.

Why a stale top count is safe

This is the part interviewers like to probe. When left moves forward, the true top count of the window may drop, yet the code never lowers top. The reason it still works: the window only grows when top reaches a new record, and a new record can only come from a real window that really contains that many copies of one letter. While top is stale, the window may hold an invalid stretch, but it is only sliding at a length that was already achieved by a valid window earlier. So the final window length equals the best valid length, and the function returns len(s) - left, which is that final length.

If that argument feels slippery under pressure, there is a version that is easier to defend: loop over each of the 26 letters, and for each letter run a window that counts how many positions are not that letter, shrinking while that count exceeds k. It is O(26 × n), still linear, and every window it measures is truly valid. Offer it if the interviewer pushes back on the stale count.

A short trace

Run MMRMQ with k = 1. After M, M the window is length 2 with top 2, zero edits needed. Adding R gives length 3, top 2, one edit, still fine. Adding M gives length 4, top 3, one edit, fine. Adding Q gives length 5, top 3, two edits, too many, so left steps past the first M. The loop ends with left at 1 and the function returns 5 minus 1, which is 4.

Complexity

Time and extra space for each approach
ApproachTimeExtra space
Every window, recounted from scratchO(n³)O(alphabet)
Every start with a running countO(n²)O(alphabet)
One window per target letterO(alphabet × n)O(1)
Single window with a stale top countO(n)O(alphabet)
Time and extra space for each approach. Scroll sideways on a small screen.

Edge cases to test

  • Empty string: the answer is 0, and the loop body never runs.
  • k = 0: the answer is the longest run that already exists.
  • k at least the string length: the whole string.
  • A string of one repeated letter: the whole string, with the budget unused.
  • Every letter different, like RSTU: the answer is k + 1, capped at the length.

Where people slip

  • Recomputing the most common letter by scanning the count table on every shrink, then claiming O(n). It is O(26n) in that case, which is fine, but say so.
  • Using a while loop to shrink and then also lowering top by guessing. Either keep the stale count with the argument above, or recompute it honestly.
  • Returning the number of edits used instead of the window length.
  • Mixing up the test direction: the window is invalid when the needed edits are greater than k, not greater than or equal.
  • Forgetting that the window length is right - left + 1 when right is the current index.

Follow-up questions

  • What if the input is a binary array and you may flip up to k zeros? It is the same window with only two symbols, and you can count zeros directly.
  • What if the alphabet is all of Unicode? Use a hash map for counts; the stale-top trick still holds.
  • Can you return the stretch itself, not only its length? Record left and right whenever the window grows.
  • What if edits cost different amounts per letter? The window test changes to a cost sum, and the stale-count shortcut no longer applies.

Explaining it in the interview

Fictional example

How a candidate might walk through it
Candidate
For any window, the cheapest fix keeps the most common letter and rewrites the rest, so the cost is length minus that count. I want the longest window where that cost is at most k.
Candidate
I'll slide a window. Right moves every step. If the cost goes over k, left moves one step, so the window never gets shorter.
Candidate
I keep the highest count I've ever seen rather than the current one. The window only grows when that number sets a new record, and a record always comes from a real valid window, so the final length is the answer. Linear time, and the table has 26 entries.

Longest Substring Without Repeating Characters uses the same two moving indexes with a different rule for when to shrink. Permutation in String is the fixed-size version of a counting window. For the stack problems in this set, start with Daily Temperatures, and see the coding problems hub for every pattern.

Practicing it with Natively

When you rehearse this problem on a Mac or Windows computer, Natively can take a screenshot of the prompt and talk through why the edit cost is length minus the top count, then point out the stale-count question before an interviewer does. It also writes a transcript of your mock round, which makes it easy to check whether you justified the window or only coded it. More on that in the AI assistant for coding interviews overview.

Questions people ask

How do you solve Longest Repeating Character Replacement?

Use a sliding window. A window can be made uniform with length minus its most common letter's count edits, so grow the window to the right and slide the left edge forward whenever that number exceeds k. It runs in O(n) time.

Why doesn't the solution decrease the max count when the window shrinks?

The window only grows when the max count sets a new record, and every record comes from a real window that was valid. A stale value can let the window slide at an old length, but never grow past the true best, so the answer stays correct.

What is the time complexity of Longest Repeating Character Replacement?

O(n) for the single sliding window, with a count table bounded by the alphabet size. Running one window per letter is O(26n), which is also linear.

What pattern is Longest Repeating Character Replacement?

A variable-size sliding window with a frequency count. It is a close relative of Longest Substring Without Repeating Characters and of the max consecutive ones with k flips problem.

Where to go next

Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.

Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.

Keep reading

Put it on your own machine.

A live-conversation assistant that runs locally. Your conversations stay on your machine.

macOS 12+ · Windows 10/11

© 2026 Natively AI Private Limited

Source-available under the Natively Personal Use Source License v1.0 · IP geolocation by DB-IP