Interview Bootcamp

0% completed

Solution: Longest Substring with K Distinct Characters

Problem Statement

Given a string, find the length of the longest substring in it with no more than K distinct characters.

You can assume that K is less than or equal to the length of the given string.

Example 1:

Input: str="araaci", K=2  
Output: 4  
Explanation: The longest substring with no more than '2' distinct characters is "araa".

Example 2:

Input: str="araaci", K=1  
Output: 2  
Explanation: The longest substring with no more than '1' distinct characters is "aa".

Example 3:

Input: str="cbbebi", K=3  
Output: 5

.....

.....

.....

Like the course? Get enrolled and start learning!
A

Anthony DiFede

· 4 years ago

I believe I accounted for the edge cases... As long as you encounter a letter you've seen before, make the window start = window end since you will only be caring about a substring with no duplicates. Image