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 with at most k distinct letters

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

Given a string s and an integer k, return the length of the longest substring that contains at most k distinct characters.

Examples

InputOutputWhy
s = "eceba", k = 23"ece".
s = "aa", k = 12
s = "abc", k = 00No non-empty substring has zero distinct characters.

Constraints

  • 0 ≤ |s| ≤ 5 × 10⁴
  • 0 ≤ k ≤ 50

Hints

Hint 1

If a substring has at most k distinct letters, so does every substring inside it. That is what makes a window work.

Hint 2

Keep a count for each letter in the window. The number of keys is the number of distinct letters.

Hint 3

Extend the right end. While there are more than k keys, remove the left letter, deleting its key when the count reaches 0.

Where people lose marks

  • Shrinking with if instead of while: one removal may not bring the count of keys down.
  • Leaving zero counts in the map, so its size never falls.
  • k = 0: the loop shrinks every window to empty, and the answer is 0.
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.