K most occurring strings | Function that returns list of K most frequent strings ; Hash map to store the frequency of each string ; Set the default frequency of each string 0 ; Using a priority queue to store the strings in accordance of the frequency and alphabetical order ( if frequency is equal ) Lambda expression is used set the priority , if frequencies are not equal than the string with greater frequency is returned else the string which is lexically smaller is returned ; Traverse the HashMap ; Remove top ( N - K ) elements ; Order queue has K most frequent strings in a reverse order ; Reverse the ArrayList so as to get in the desired order ; Driver Code ; Given array ; Function Call ; Print the K most occurring strings
function frequentWords ( arr , K ) { var Freq = new Map ( ) ; for ( var word of arr ) { Freq . set ( word , Freq . has ( word ) ? Freq . get ( word ) : 0 ) ; } var Order = [ ] ; for ( var word of [ ... Freq . keys ( ) ] ) { Order . push ( word ) ; if ( Order . length > K ) { Order . pop ( ) ; } } var ans = [ ] ; Order . sort ( ( a , b ) => a [ 0 ] - b [ 0 ] ) ; while ( Order . length != 0 ) { ans . push ( Order [ Order . length - 1 ] ) Order . pop ( ) ; } ans . reverse ( ) ; return ans ; } var N = 3 , K = 2 ; var arr = [ ] ; arr . push ( " " ) ; arr . push ( " " ) ; arr . push ( " " ) ; var ans = frequentWords ( arr , K ) ; for ( var word of ans ) { document . write ( word + " " ) ; }