Count of substrings having all distinct characters | Function to count total number of valid substrings ; Stores the count of substrings ; Stores the frequency of characters ; Initialised both pointers to beginning of the string ; If all characters in substring from index i to j are distinct ; Increment count of j - th character ; Add all substring ending at j and starting at any index between i and j to the answer ; Increment 2 nd pointer ; If some characters are repeated or j pointer has reached to end ; Decrement count of j - th character ; Increment first pointer ; Return the final count of substrings ; Driver code
def countSub ( Str ) : NEW_LINE INDENT n = len ( Str ) NEW_LINE ans = 0 NEW_LINE cnt = 26 * [ 0 ] NEW_LINE i , j = 0 , 0 NEW_LINE while ( i < n ) : NEW_LINE INDENT if ( j < n and ( cnt [ ord ( Str [ j ] ) - ord ( ' a ' ) ] == 0 ) ) : NEW_LINE INDENT cnt [ ord ( Str [ j ] ) - ord ( ' a ' ) ] += 1 NEW_LINE ans += ( j - i + 1 ) NEW_LINE j += 1 NEW_LINE DEDENT else : NEW_LINE INDENT cnt [ ord ( Str [ i ] ) - ord ( ' a ' ) ] -= 1 NEW_LINE i += 1 NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT Str = " gffg " NEW_LINE print ( countSub ( Str ) ) NEW_LINE