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

ag

· 4 years ago

how about this solution, basically once we encounter a duplicate then just clear the set

int windowStart = 0, maxLength = 0; Set cache = new HashSet(); for (int windowEnd = 0; windowEnd < str.length(); windowEnd++) { char c = str.charAt(windowEnd); if (cache.contains(c)) { cache.clear(); windowStart = windowEnd; } cache.add(c); maxLength = Math.max(maxLength, windowEnd - windowStart + 1); }

return maxLength;

Show 1 reply