Count Frequency of each element
TreeMap < Integer , Integer > freq = new TreeMap < > ( ) ; for ( int i = 0 ; i < n ; i ++ ) if ( freq . containsKey ( arr [ i ] ) ) freq . put ( arr [ i ] , 1 + freq . get ( arr [ i ] ) ) ; else freq . put ( arr [ i ] , 1 ) ;