To store the count of each a [ i ] in a map
HashMap < Integer , Integer > cnt = new HashMap < Integer , Integer > ( ) ; for ( int i = 0 ; i < n ; i ++ ) { if ( cnt . containsKey ( arr [ i ] ) ) { cnt . put ( arr [ i ] , cnt . get ( arr [ i ] ) + 1 ) ; } else { cnt . put ( arr [ i ] , 1 ) ; } }