compute the max value in the array and create frequency array of size max_val + 1. We can also use HashMap to store frequencies . We have used an array to keep remaining code simple .
let max_val = 0 ; for ( let i = 0 ; i < n ; i ++ ) max_val = Math . max ( max_val , arr [ i ] ) ; let freq = new Array ( max_val + 1 ) ; for ( let i = 0 ; i < freq . length ; i ++ ) { freq [ i ] = 0 ; } for ( let i = 0 ; i < n ; i ++ ) freq [ arr [ i ] ] ++ ;