Frequent Words
Solve a medium-level problem to find the K most frequent words in sentences.
Problem statement
Given a list of sentences and an integer
Example
Sample input
words: ["i learn to code", "i love to code"]K: 2
Sample output
["code", "i"]
Explanation
"i", "code" and "to" are the three most frequent words with a frequency of two. But only "i" and "code" are returned as output due to lexicographical sorting.
Try it yourself
Try to solve the problem yourself before reading the solution.
Intuition
Sorting-based approach
The most intuitive method to solve this problem is sorting with a custom comparator. The comparator first compares the frequency of two words and sorts them in descending order of frequency. If the frequency for two words is the same, then they are sorted in alphabetically ascending (lexicographical) order.
Let the total number of words combined from all the sentences be
The frequency of each word is stored in an unordered map. The size of the map can be
Hashmap and priority queue-based approach
We ignored one helpful parameter provided in the input in the previous sorting-based approach. We only need to find the top