Skip to content
Work Practice Products Coding interviews Machine learning coding Quant developer HFT course Blog Method Why me About Enquire Book a call

Coding · Sliding window

Longest run of one letter after k changes

Medium · Target 25 minutes · Sliding window· Type asked at

Given an uppercase string s and an integer k, you may change at most k characters into any other uppercase letter. Return the length of the longest substring you can turn into a single repeated letter.

Examples

InputOutputWhy
s = "ABAB", k = 24Change both A's, or both B's.
s = "AABABBA", k = 14"AABA" with the B changed, or "ABBB" with the A changed.
s = "ABC", k = 01

Constraints

  • 1 ≤ |s| ≤ 10⁵
  • s is uppercase English letters
  • 0 ≤ k ≤ |s|

Hints

Hint 1

Which letter should a window become? The one it already holds most of.

Hint 2

A window can be fixed with (length − count of its most common letter) changes.

Hint 3

Keep counts and the largest count seen. When the window needs more than k changes, move the left end by one. Why is it safe never to lower the largest count?

Where people lose marks

  • Choosing the letter to keep in advance. Each window keeps its own most common letter.
  • Reading the window's contents as the answer. With a never-lowered top the window can hold a substring that is not fixable at that moment; only its length is meaningful.
  • Returning top + k: it can exceed the length of the string.
Console⌘/Ctrl + Enter runs

Write a solution and run it against the real test table.


Keep going

Preparing for a real process? Quant interview preparation, or book a free 20-minute call.