Length of the smallest sub | Python 3 program to find the length of the smallest substring consisting of maximum distinct characters ; Find maximum distinct characters in any string ; Initialize all character 's  count with 0 ; Increase the count in array if a character is found ; size of given string ; Find maximum distinct characters in any string ; result ; Brute force approach to find all substrings ; We have to check here both conditions together 1. substring ' s ▁ distinct ▁ characters ▁ is ▁ equal ▁ ▁ to ▁ maximum ▁ distinct ▁ characters ▁ ▁ 2 . ▁ substring ' s length should be minimum ; Driver Code ; Input String
NO_OF_CHARS = 256 NEW_LINE def max_distinct_char ( str , n ) : NEW_LINE INDENT count = [ 0 ] * NO_OF_CHARS NEW_LINE for i in range ( n ) : NEW_LINE INDENT count [ ord ( str [ i ] ) ] += 1 NEW_LINE DEDENT max_distinct = 0 NEW_LINE for i in range ( NO_OF_CHARS ) : NEW_LINE INDENT if ( count [ i ] != 0 ) : NEW_LINE INDENT max_distinct += 1 NEW_LINE DEDENT DEDENT return max_distinct NEW_LINE DEDENT def smallesteSubstr_maxDistictChar ( str ) : NEW_LINE INDENT n = len ( str ) NEW_LINE max_distinct = max_distinct_char ( str , n ) NEW_LINE minl = n NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( n ) : NEW_LINE INDENT subs = str [ i : j ] NEW_LINE subs_lenght = len ( subs ) NEW_LINE sub_distinct_char = max_distinct_char ( subs , subs_lenght ) NEW_LINE if ( subs_lenght < minl and max_distinct == sub_distinct_char ) : NEW_LINE INDENT minl = subs_lenght NEW_LINE DEDENT DEDENT DEDENT return minl NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT str = " AABBBCBB " NEW_LINE l = smallesteSubstr_maxDistictChar ( str ) ; NEW_LINE print ( " The ▁ length ▁ of ▁ the ▁ smallest ▁ substring " , " consisting ▁ of ▁ maximum ▁ distinct " , " characters ▁ : " , l ) NEW_LINE DEDENT