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
function countSub ( str ) { var n = str . length ; var ans = 0 ; var cnt = Array ( 26 ) . fill ( 0 ) ; var i = 0 , j = 0 ; while ( i < n ) { if ( j < n && ( cnt [ str [ j ] . charCodeAt ( 0 ) - ' ' . charCodeAt ( 0 ) ] == 0 ) ) { cnt [ str [ j ] . charCodeAt ( 0 ) - ' ' . charCodeAt ( 0 ) ] ++ ; ans += ( j - i + 1 ) ; j ++ ; } else { cnt [ str [ i ] . charCodeAt ( 0 ) - ' ' . charCodeAt ( 0 ) ] -- ; i ++ ; } } return ans ; } var str = " " ; document . write ( countSub ( str ) ) ;