Find frequency of each element in a limited range array in less than O ( n ) time | Java program to count number of occurrences of each element in the array ; It prints number of occurrences of each element in the array . ; HashMap to store frequencies ; traverse the array ; update the frequency ; traverse the hashmap ; Driver function
import java . io . * ; import java . util . * ; class GFG { static void findFrequency ( int [ ] arr , int n ) { Map < Integer , Integer > mp = new HashMap < Integer , Integer > ( ) ; for ( int i = 0 ; i < n ; i ++ ) { if ( ! mp . containsKey ( arr [ i ] ) ) mp . put ( arr [ i ] , 0 ) ; mp . put ( arr [ i ] , mp . get ( arr [ i ] ) + 1 ) ; } for ( Map . Entry < Integer , Integer > kvp : mp . entrySet ( ) ) { System . out . println ( " Element ▁ " + kvp . getKey ( ) + " ▁ occurs ▁ " + kvp . getValue ( ) + " ▁ times " ) ; } } public static void main ( String [ ] args ) { int [ ] arr = { 1 , 1 , 1 , 2 , 3 , 3 , 5 , 5 , 8 , 8 , 8 , 9 , 9 , 10 } ; int n = arr . length ; findFrequency ( arr , n ) ; } }