1+ # Longest Substring with K Distinct Characters (medium)
2+ # Given a string, find the length of the longest substring in it with no more than K distinct characters.
3+ # You can assume that K is less than or equal to the length of the given string.
4+ 5+ # Input: String="araaci", K=2
6+ # Output: 4
7+ # Explanation: The longest substring with no more than '2' distinct characters is "araa".
8+ 9+ def longest_substring_with_k_distinct (str1 , k ):
10+ window_start = 0
11+ max_length = 0
12+ char_frequency = {}
13+ 14+ # in the following loop we'll try to extend the range [window_start, window_end]
15+ for window_end in range (len (str1 )):
16+ right_char = str1 [window_end ]
17+ if right_char not in char_frequency :
18+ char_frequency [right_char ] = 0
19+ char_frequency [right_char ] += 1
20+ 21+ # shrink the sliding window, until we are left with 'k' distinct characters in the char_frequency
22+ while len (char_frequency ) > k :
23+ left_char = str1 [window_start ]
24+ char_frequency [left_char ] -= 1
25+ if char_frequency [left_char ] == 0 :
26+ del char_frequency [left_char ]
27+ window_start += 1 # shrink the window
28+ # remember the maximum length so far
29+ max_length = max (max_length , window_end - window_start + 1 )
30+ return max_length
31+ 32+ 33+ def main ():
34+ print ("Length of the longest substring: " + str (longest_substring_with_k_distinct ("araaci" , 2 ))) # 4
35+ print ("Length of the longest substring: " + str (longest_substring_with_k_distinct ("araaci" , 1 ))) # 2
36+ print ("Length of the longest substring: " + str (longest_substring_with_k_distinct ("cbbebi" , 3 ))) # 5
37+ 38+ 39+ main ()
0 commit comments