← Whiteboard questions

Longest Repeating Character Replacement

Find the longest run you can make with at most k changes

DSA, Medium, Sliding Window

Which structure or algorithm, and what does it cost.

You get a string s of capital letters and a whole number k. You may pick up to k positions in s and overwrite each with any capital letter. After that, look for the longest stretch of consecutive characters that are all the same letter. Return the best length you can reach.

Examples

Input s = "QQRQSQQ", k = 1
Output 4
Why change the R to Q and the window "QQQQ" has length 4. A window of 5 would need two changes.
Input s = "MNMN", k = 0
Output 1
Why no change is allowed and no letter repeats side by side, so the best run is 1.
Input s = "PQRS", k = 3
Output 4
Why three changes turn any three letters into the fourth, so the whole string becomes one letter.

Constraints

Your answer must contain

Target Aim for O(n) time and O(1) memory.

Hints

Try the problem first. Open one hint at a time.

Hint 1 a nudge

Look at one window. How many changes does it need to become a single letter?

Hint 2 the approach

A window needs its length minus the count of its most common letter. If that is at most k, the window is valid.

Hint 3 the key step

Grow the window to the right. When the changes needed go above the limit, move the left side in by one. Track the best size seen.

Walkthrough

Full walkthrough brute force to best

Brute force

Check every substring. Count its letters, find the most common one, and test whether length minus that count is at most k. With running counts this is O(n^2) time and O(1) memory. For 100,000 letters it is about 5 billion substrings, too slow.

Better method

Pick a target letter, one of the 26. Slide a window that keeps at most k letters different from the target, and record its longest size. Do this for each letter and keep the maximum. This is O(26 * n) time and O(1) memory. It is correct, but it makes 26 passes.

Best method

Use one window with two sides, left and right, and a count of each letter inside it. Move right one step at a time and add its letter. Keep top, the largest letter count seen in any window so far. To become one letter, a window needs as many changes as its length minus the true count of its most common letter. It is valid when that number is at most k. If length minus top is above k, remove the letter at left and move left by one, so the window slides and does not grow. A stale top cannot give a wrong answer. The window only becomes larger when top goes up, and that happens only when a real window has a higher count. So the window size never beats the true best. The answer is the largest window size seen.

Hand trace

Run on "QQRQSQQ" with k = 1. Right 0 and 1: window "QQ", top 2, size 2. Right 2 (R): size 3, top 2, changes 1, fine. Right 3 (Q): size 4, top 3, changes 1, fine, best 4. Right 4 (S): size 5, top 3, changes 2 is above 1, so drop the Q at left 0, window "QRQS", size 4. Right 5 (Q): size 5, changes 2, drop the Q at left 1, size 4. Right 6 (Q): size 5, changes 2, drop the R at left 2, size 4. The best is 4.

Code

def longest_after_changes(s, k):
    counts = {}
    left = 0
    top = 0
    best = 0
    for right, ch in enumerate(s):
        counts[ch] = counts.get(ch, 0) + 1
        top = max(top, counts[ch])
        if (right - left + 1) - top > k:
            counts[s[left]] -= 1
            left += 1
        best = max(best, right - left + 1)
    return best

Time and memory

O(n) time, because right moves n steps and left never moves back. O(1) memory, because there are at most 26 letter counts.

Common mistakes

  • Using the count of the letter at right or at left instead of the most common letter. Only the most common letter needs no change.
  • Moving left when length minus the top count is equal to k. A window that needs exactly k changes is still valid. Shrink only above k.
  • Counting letters from the whole string and not from the window. The substring must be consecutive.

Related problems

More Sliding Window problems
Longest Repeating Character Replacement walkthrough