Longest Repeating Character Replacement
1Try it yourself first
Think for 20-30 minutes before you open any hint. Being stuck is where the learning happens.
Only for you, saved in this browser. After you see the approach you will compare it with your idea.2What is being asked
You may change at most k characters. Find the longest stretch you can turn into one repeated letter.
3Hint ladder
Take one rung at a time. Stop as soon as the idea clicks.
- Hint 1In a window, which letter should you keep and which should you change?
- Hint 2The number of changes needed = window length - count of the most common letter.
4The approach
Have you tried the hints? The approach is built as a path from the obvious way to the clever one.
A fence has planks painted in different colours and you have k small paint cans. Pick a stretch of fence to make all one colour. Keep the colour that already dominates and repaint the rest. The stretch is possible if the number of off-colour planks is at most k, i.e. stretch length minus the count of the dominant colour is at most k. Make the stretch as long as you can.
- The obvious way
Try every substring and count: O(n² x 26).
- The key insight
Grow a window to the right, keeping a count per letter and the highest count seen in any window. If window length - highest count exceeds k, the window needs too many repaints: slide it by moving the left edge one step. The highest count never has to shrink, because only a window with a larger highest count can give a longer answer.
- The algorithm
- Counts per letter, left edge at the start, highest count 0.
- Add the new letter on the right; update the highest count.
- Window length - highest count > k? Remove the left letter and move the left edge on by one.
- Best = the largest window length seen.
Watch it run
Examplefence = "AABABBA", k = 1
Window "AAB": most common A (2), so 1 plank to repaint, allowed. Width 3.
best 3
Where people slip
- Never recompute the highest count downward: a stale larger value only keeps windows that cannot beat the answer.
How close was your idea?
You did not write an idea, and that is fine.
Be honest with yourself. This sets your revision list.
5Code
Try writing it yourself from the steps first. Then compare.
def character_replacement(text, k):
counts = {}
left = most_common = best = 0
for right, letter in enumerate(text):
counts[letter] = counts.get(letter, 0) + 1
most_common = max(most_common, counts[letter])
while (right - left + 1) - most_common > k: # too many planks to repaint
counts[text[left]] -= 1
left += 1
best = max(best, right - left + 1)
return bestNow close this and write it again from memory, in the language you will use in the interview. Reattempt after 1 day, 7 days and about 30 days.
6Still stuck? Watch a video
Seeing someone explain it out loud can make it click. Try the video after you have read the approach above.