Sub | Function that counts all the sub - strings of length ' k ' which have all identical characters ; count of sub - strings , length , initial position of sliding window ; dictionary to store the frequency of the characters of sub - string ; increase the frequency of the character and length of the sub - string ; if the length of the sub - string is greater than K ; remove the character from the beginning of sub - string ; if the length of the sub string is equal to k and frequency of one of its characters is equal to the length of the sub - string i . e . all the characters are same increase the count ; display the number of valid sub - strings ; Driver code
def solve ( s , k ) : NEW_LINE INDENT count , length , pos = 0 , 0 , 0 NEW_LINE m = dict . fromkeys ( s , 0 ) NEW_LINE for i in range ( len ( s ) ) : NEW_LINE INDENT m [ s [ i ] ] += 1 NEW_LINE length += 1 NEW_LINE if length > k : NEW_LINE INDENT m [ s [ pos ] ] -= 1 NEW_LINE pos += 1 NEW_LINE length -= 1 NEW_LINE DEDENT if length == k and m [ s [ i ] ] == length : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT print ( count ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT s = " aaaabbbccdddd " NEW_LINE k = 4 NEW_LINE solve ( s , k ) NEW_LINE DEDENT