start from right side of string
for ( let i = len - 1 ; i >= 0 ; i -- ) { count [ str [ i ] . charCodeAt ( ) - ' ' . charCodeAt ( ) ] ++ ; for ( let j = str [ i ] . charCodeAt ( ) - ' ' . charCodeAt ( ) + 1 ; j < MAX_CHAR ; j ++ ) { ans [ i ] += count [ j ] ; } } for ( let i = 0 ; i < len ; i ++ ) { document . write ( ans [ i ] + " " ) ; } }