Precompute the Suffix 2D array .
for ( let i = n - 2 ; i >= 0 ; i -- ) { for ( let j = 0 ; j < MAX_CHAR ; j ++ ) r [ j ] [ i ] += r [ j ] [ i + 1 ] ; r [ s [ i ] . charCodeAt ( 0 ) - ' ' . charCodeAt ( 0 ) ] [ i ] ++ ; } }