1+ '''
2+ Given a string, find the length of the longest substring in it with no more than K distinct characters
3+ Input: String="araaci", K=2
4+ Output: 4
5+ Explanation: The longest substring with no more than '2' distinct characters is "araa".
6+ Input: String="araaci", K=1
7+ Output: 2
8+ Explanation: The longest substring with no more than '1' distinct characters is "aa".
9+ Solution:
10+ ->fisrt we will add char in charfreq HashMap
11+ ->then We will expand window by adding element at window_end
12+ ->once we reach greater then k then shrink the window by removing element from start
13+ '''
14+ def longest_substring_with_k_dist (str ,k ):
15+ window_start = 0
16+ max_length = 0
17+ char_freq = {}
18+
19+ # in the following loop we'll try to expand[window_start,window_end]
20+ for window_end in range (len (str )):
21+ right_char = str [window_end ]
22+ if right_char not in char_freq :
23+ char_freq [right_char ] = 0
24+ char_freq [right_char ] += 1
25+
26+ # Shrink the sliding window, untill we are left with 'k' disctinct char in the char_freq
27+ while len (char_freq ) > k :
28+ left_char = str [window_start ]
29+ char_freq [left_char ] -= 1
30+ if char_freq [left_char ] == 0 :
31+ del char_freq [left_char ]
32+ window_start += 1 # shrink the window
33+ # remember the maximum length so far
34+ max_length = max (max_length , window_end - window_start + 1 )
35+ return max_length
36+
37+ '''
38+ Time Complexity #
39+ The time complexity of the above algorithm will be O(N) where ‘N’ is the number of characters in the input string.
40+ The outer for loop runs for all characters and the inner while loop processes each character only once,
41+ therefore the time complexity of the algorithm will be O(N+N) which is asymptotically equivalent to O(N).
42+
43+ Space Complexity #
44+ The space complexity of the algorithm is O(K)O(K), as we will be storing a maximum of ‘K+1’ characters in the HashMap.
45+ '''
0 commit comments