Longest Substring with At Most K Distinct Characters

Medium

Description

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

Examples

Input:s = "eceba", k = 2
Output:3
Explanation:

'ece' has 2 distinct characters and length 3.

Input:s = "abcabcbb", k = 3
Output:7
Explanation:

The longest substring with at most 3 distinct characters is 'abcabcb' which has characters 'a', 'b', 'c' (3 distinct) and length 7.

Input:s = "pwwkew", k = 0
Output:0
Explanation:

When k = 0, no characters are allowed, so the longest valid substring has length 0.

Constraints

  • 1 ≤ s.length ≤ 5 * 10⁴
  • 0 ≤ k ≤ 50

Ready to solve this problem?

Practice solo or challenge other developers in a real-time coding battle!