Count substrings with different first and last characters | Function to count the substrings having different first & last character ; Stores frequency of each char ; Loop to store frequency of the characters in a Map ; To store final result ; Traversal of string ; Store answer for every iteration ; Map traversal ; Compare current char ; Print the final count ; Given string ; Length of the string ; Function Call
function countSubstring ( s , n ) { var m = new Map ( ) ; for ( var i = 0 ; i < n ; i ++ ) { if ( m . has ( s [ i ] ) ) m . set ( s [ i ] , m . get ( s [ i ] ) + 1 ) else m . set ( s [ i ] , 1 ) } var ans = 0 ; for ( var i = 0 ; i < n ; i ++ ) { var cnt = 0 ; if ( m . has ( s [ i ] ) ) m . set ( s [ i ] , m . get ( s [ i ] ) - 1 ) m . forEach ( ( value , key ) => { if ( key != s [ i ] ) { cnt += value ; } } ) ; ans += cnt ; } document . write ( ans ) ; } var S = " " ; var N = 5 ; countSubstring ( S , N ) ;