Count substrings with same first and last characters | assuming lower case only ; Calculating frequency of each character in the string . ; Computing result using counts ; Driver function
var MAX_CHAR = 26 ; function countSubstringWithEqualEnds ( s ) { var result = 0 ; var n = s . length ; var count = Array . from ( { length : MAX_CHAR } , ( _ , i ) => 0 ) ; for ( var i = 0 ; i < n ; i ++ ) count [ s . charAt ( i ) . charCodeAt ( 0 ) - ' ' . charCodeAt ( 0 ) ] ++ ; for ( var i = 0 ; i < MAX_CHAR ; i ++ ) result += ( count [ i ] * ( count [ i ] + 1 ) / 2 ) ; return result ; } var s = " " ; document . write ( countSubstringWithEqualEnds ( s ) ) ;