Practice
JavaScriptData StructuresReactConcepts
Sign in
← Back to problems

Longest Substring with At Most K Distinct

Sliding Windowmedium

Implement `longestKDistinct(s, k)` returning the length of the longest substring containing at most `k` distinct characters.

Sample tests

Input: longestKDistinct("eceba", 2)
Output: 3
Input: longestKDistinct("aa", 1)
Output: 2

+ 1 hidden test run on Submit.

Hints

Common pitfalls
  • Forgetting to delete a key when its count hits zero inflates the distinct count.

Learning resources

  • MDN: String
Approach & explanation (try first)

A window keyed by character counts keeps at most k distinct in O(n).

Loading...
⌘/Ctrl + Enter

Run your code to see results.