Longest Substring with At Most K Distinct Characters

Medium

Topics
StringSliding WindowHash Table

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

Example 1

Input:  s = "eceba", k = 2
Output: 3
Explanation: The substring "ece" has 2 distinct characters and length 3.

Example 2

Input:  s = "aa", k = 1
Output: 2
Explanation: The whole string has only 1 distinct character.

Example 3

Input:  s = "abc", k = 0
Output: 0
Explanation: No substring can have zero distinct characters except the empty one.

Constraints

  • 1 <= s.length <= 5 * 10^4
  • 0 <= k <= 50
  • s consists of lowercase English letters
Run ⌘' · Submit ⌘⏎