text: Count of substrings from given Ternary strings containing characters at least once | Function to count the number of substrings consists of 0 , 1 , and 2 ; Initialize frequency array of size 3 ; Stores the resultant count ; Traversing string str ; Update frequency array ; If all the characters are present counting number of substrings possible ; Update number of substrings ; Return the number of substrings ; Driver Code
code: def countSubstrings ( str ) : NEW_LINE INDENT freq = [ 0 ] * 3 NEW_LINE count = 0 NEW_LINE i = 0 NEW_LINE for j in range ( 0 , len ( str ) ) : NEW_LINE INDENT freq [ ord ( str [ j ] ) - ord ( '0' ) ] += 1 NEW_LINE while ( freq [ 0 ] > 0 and freq [ 1 ] > 0 and freq [ 2 ] > 0 ) : NEW_LINE INDENT i += 1 NEW_LINE freq [ ord ( str [ i ] ) - ord ( '0' ) ] -= 1 NEW_LINE DEDENT count += i NEW_LINE DEDENT return count NEW_LINE DEDENT str = "00021" NEW_LINE count = countSubstrings ( str ) NEW_LINE print ( count ) NEW_LINE