Count of substrings having the most frequent character in the string as first character | Function to find all substrings whose first character occurs maximum number of times ; Stores frequency of characters ; Stores character that appears maximum number of times ; Stores max frequency of character ; Updates frequency of characters ; Update maxfreq ; Character that occures maximum number of times ; Update the maximum frequency character ; Stores all count of substrings ; Traverse over string ; Get the current character ; Update count of substrings ; Return the count of all valid substrings ; Driver Code ; Function Call
function substringCount ( s ) { var freq = new Array ( 26 ) . fill ( 0 ) ; var max_char = " " ; var maxfreq = - 21474836487 ; for ( var i = 0 ; i < s . length ; i ++ ) { freq [ s [ i ] . charCodeAt ( 0 ) - " " . charCodeAt ( 0 ) ] ++ ; if ( maxfreq < freq [ s [ i ] . charCodeAt ( 0 ) - " " . charCodeAt ( 0 ) ] ) maxfreq = freq [ s [ i ] . charCodeAt ( 0 ) - " " . charCodeAt ( 0 ) ] ; } for ( var i = 0 ; i < 26 ; i ++ ) { if ( maxfreq === freq [ i ] ) { max_char = String . fromCharCode ( i + " " . charCodeAt ( 0 ) ) ; break ; } } var ans = 0 ; for ( var i = 0 ; i < s . length ; i ++ ) { var ch = s [ i ] ; if ( max_char === ch ) { ans += s . length - i ; } } return ans ; } var S = " " ; document . write ( substringCount ( S ) ) ;