Mid/Senior

Longest Substring with At Most K Distinct Characters

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

A substring is a contiguous, non-empty sequence of characters within s. Your solution should efficiently track character frequencies while considering contiguous substrings.

Example 1
Inputs = "eceba", k = 2
Output3
The substring "ece" has length 3 and contains at most 2 distinct characters.
Example 2
Inputs = "aa", k = 1
Output2
The entire string "aa" has length 2 and contains only 1 distinct character.

Constraints

  • 1 <= s.length <= 5 * 10^4
  • 0 <= k <= 50
  • s consists of English letters.

Asked at 12 companies

</>

Your Solution

(Ctrl/Cmd + Enter)

Switching Language

Loading template...

Loading...

Sign in to save your progress

AI code evaluation

Get a correctness verdict, missed edge cases, and complexity analysis of your solution.

Sign in to evaluate