Number of substrings with count of each character as k | Python3 program to count number of substrings with counts of distinct characters as k . ; Returns true if all values in freq [ ] are either 0 or k . ; Returns count of substrings where frequency of every present character is k ; Pick a starting point ; Initialize all frequencies as 0 for this starting point ; One by one pick ending points ; Increment frequency of current char ; If frequency becomes more than k , we can 't have more substrings  starting with i ; If frequency becomes k , then check other frequencies as well ; Driver Code
MAX_CHAR = 26 NEW_LINE def check ( freq , k ) : NEW_LINE INDENT for i in range ( 0 , MAX_CHAR ) : NEW_LINE INDENT if ( freq [ i ] and freq [ i ] != k ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT def substrings ( s , k ) : NEW_LINE INDENT for i in range ( 0 , len ( s ) ) : NEW_LINE INDENT freq = [ 0 ] * MAX_CHAR NEW_LINE for j in range ( i , len ( s ) ) : NEW_LINE INDENT index = ord ( s [ j ] ) - ord ( ' a ' ) NEW_LINE freq [ index ] += 1 NEW_LINE if ( freq [ index ] > k ) : NEW_LINE INDENT break NEW_LINE DEDENT elif ( freq [ index ] == k and check ( freq , k ) == True ) : NEW_LINE INDENT res += 1 NEW_LINE DEDENT DEDENT DEDENT return res NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT s = " aabbcc " NEW_LINE k = 2 NEW_LINE print ( substrings ( s , k ) ) NEW_LINE s = " aabbc " ; NEW_LINE k = 2 ; NEW_LINE print ( substrings ( s , k ) ) NEW_LINE DEDENT