Longest substring with K unique characters using Binary Search | Function that returns True if there is a sub of length len with <= k unique characters ; Size of the ; Map to store the characters and their frequency ; Update the map for the first sub ; Check for the rest of the subs ; Add the new character ; Remove the first character of the previous window ; Update the map ; Function to return the length of the longest sub which has K unique characters ; Check if the complete contains K unique characters ; Size of the ; Apply binary search ; Driver code
def isValidLen ( s , lenn , k ) : NEW_LINE INDENT n = len ( s ) NEW_LINE mp = dict ( ) NEW_LINE right = 0 NEW_LINE while ( right < lenn ) : NEW_LINE INDENT mp [ s [ right ] ] = mp . get ( s [ right ] , 0 ) + 1 NEW_LINE right += 1 NEW_LINE DEDENT if ( len ( mp ) <= k ) : NEW_LINE INDENT return True NEW_LINE DEDENT while ( right < n ) : NEW_LINE INDENT mp [ s [ right ] ] = mp . get ( s [ right ] , 0 ) + 1 NEW_LINE mp [ s [ right - lenn ] ] -= 1 NEW_LINE if ( mp [ s [ right - lenn ] ] == 0 ) : NEW_LINE INDENT del mp [ s [ right - lenn ] ] NEW_LINE DEDENT if ( len ( mp ) <= k ) : NEW_LINE INDENT return True NEW_LINE DEDENT right += 1 NEW_LINE DEDENT return len ( mp ) <= k NEW_LINE DEDENT def maxLenSubStr ( s , k ) : NEW_LINE INDENT uni = dict ( ) NEW_LINE for x in s : NEW_LINE INDENT uni [ x ] = 1 NEW_LINE DEDENT if ( len ( uni ) < k ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT n = len ( s ) NEW_LINE lo = - 1 NEW_LINE hi = n + 1 NEW_LINE while ( hi - lo > 1 ) : NEW_LINE INDENT mid = lo + hi >> 1 NEW_LINE if ( isValidLen ( s , mid , k ) ) : NEW_LINE INDENT lo = mid NEW_LINE DEDENT else : NEW_LINE INDENT hi = mid NEW_LINE DEDENT DEDENT return lo NEW_LINE DEDENT s = " aabacbebebe " NEW_LINE k = 3 NEW_LINE print ( maxLenSubStr ( s , k ) ) NEW_LINE