Problem Description
You are given a list of words present in a book. Your younger brother is curious to know the K most frequent words in the book, you have to find them.
Your answer should be sorted by frequency from highest to lowest. If two words have the same frequency, then the word with the lower alphabetical order should come first.
Input Format
There are three lines of input
The first line contains N, which is the number of input strings.
The second line contains N space-separated input strings (S).
The third line contains the value of K.
Output format
Print the K most frequent words present inside the book, each in a new line. If two words have the same frequency, then the word with the lower alphabetical order should come first.
Sample Input
3
car bus car
2
Sample Output
car
bus
Solution
Using Priority Queue
/* Using Priority Queue
* Note - Javascript has no inbuilt data structure for Priority Queue , so one has to develop it from scratch.
*/
function frequentWords(words, k) {
const obj = new PriorityQueue(k)
const map = {}
for (let val of words) {
if (map[val]) {
map[val] += 1
} else {
map[val] = 1
}
}
for (let val in map) {
let temp_obj = { frequency: map[val], value: val }
obj.add(temp_obj)
}
return obj.getValue()
}
Without Priority Queue
/* Using Priority Queue */
function frequentWords(words, k) {
let hash = {};
for (let word of words) {
hash[word] = hash[word]+1||1;
}
let result = Object.keys(hash).sort((a,b)=>{
let countCompare = hash[b] - hash[a];
if (countCompare == 0) return a.localeCompare(b);
else return countCompare;
}
);
return result.slice(0, k);
}