Store counts of all elements .
let count = new Map ( ) ; for ( let i = 0 ; i < n ; i ++ ) { if ( count . has ( a [ i ] ) ) { count . set ( a [ i ] , count . get ( a [ i ] ) + 1 ) ; } else { count . set ( a [ i ] , 1 ) ; } } }