Count of lexicographically smaller characters on right | Function to count the smaller characters on the right of index i ; store the length of string ; initialize each elements of arr to zero ; array to store count of smaller characters on the right side of that index ; initialize the variable to store the count of characters smaller than that at index i ; adding the count of characters smaller than index i ; print the count of characters smaller than index i stored in ans array ; Driver Code
function countSmaller ( str ) { var n = str . length ; var arr = Array ( 26 ) . fill ( 0 ) ; var ans = Array ( n ) ; for ( var i = n - 1 ; i >= 0 ; i -- ) { arr [ str [ i ] . charCodeAt ( 0 ) - ' ' . charCodeAt ( 0 ) ] ++ ; var ct = 0 ; for ( var j = 0 ; j < str [ i ] . charCodeAt ( 0 ) - ' ' . charCodeAt ( 0 ) ; j ++ ) { ct += arr [ j ] ; } ans [ i ] = ct ; } for ( var i = 0 ; i < n ; i ++ ) { document . write ( ans [ i ] + " " ) ; } } var str = " " ; countSmaller ( str ) ;