Insert all elements in hash .
Map < Integer , Integer > count = new HashMap < Integer , Integer > ( ) ; for ( int i = 0 ; i < n ; i ++ ) { int key = arr [ i ] ; if ( count . containsKey ( key ) ) { int freq = count . get ( key ) ; freq ++ ; count . put ( key , freq ) ; } else count . put ( key , 1 ) ; }