DIY: Longest Substring with At Most K Distinct Characters

Solve the interview question "Longest Substring with At Most K Distinct Characters" in this lesson.

Problem statement

Given a string, find the length of the longest substring tt that contains at most k distinct characters.

Input

The input will contain a string s and an integer k. The following is an example input:

"cdaba", 3

Output

The output will be an integer representing the length of the longest substring. The following is an example output:

4

The substring daba is the longest string in the above input that has 3 distinct characters.

Coding exercise

Implement the length_of_longest_substring_k_distinct(s, k) function, where s is the string and k is the integer. The function returns the length of the longest substring that has k distinct characters.

Level up your interview prep. Join Educative to access 80+ hands-on prep courses.