...

/

Frequent Words

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 KK, return the KK most frequent words present in those sentences, sorted by their frequency. In case there's a tie in frequency, sort the words lexicographically.

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.

Solve frequent words in C++

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 NN. The best-case time complexity of a standard sorting algorithm like merge sort is O(N log(N))O(N \space log(N)).

The frequency of each word is stored in an unordered map. The size of the map can be O(N)O(N), where NN is the number of unique words. Also, the space required by a sorting algorithm is O(N)O(N). So the final space complexity is O(N)O(N).

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 KK ...

Access this course and 1600+ top-rated courses and projects.