K Most Frequent Words

You have been given an array/list 'WORDS' of 'N' non-empty words, and an integer 'K'. Your task is to return the 'K' most frequent words sorted by their frequency from highest to lowest.

Note:

If two words have the same frequency then the lexicographically smallest word should come first in your answer.

Follow up:

Can you solve it in O(N * logK) time and O(N) extra space? 
Input Format:
The first line of input contains two integers, N and K, where N is the number of the words and, K denotes the number of words to return.

The next line contains N single space-separated words. Each word consists of only lowercase Latin letters.
Output Format:
For each input, print K single space-separated words, where the ith word denotes the ith most frequent word.
Note:
You are not required to print the expected output; it has already been taken care of. Just implement the function.
Constraints:
1 <= N <= 10^5
1 <= K <= number of unique words

Time Limit: 1sec
AnswerBot
1y

Given an array of words and an integer k, return the k most frequent words sorted by frequency.

  • Use a hashmap to count the frequency of each word

  • Use a priority queue to keep track of the k most frequen...read more

CodingNinjas
author
2y

Brute force was to iterate on every collection id/name over every file given and then group them up. That was not an optimized solution.

Optimal way is to use Set to remove duplicates first and then us...read more

CodingNinjas
author
2y
Using Sorting

We use a hashmap<key, value> to store the frequencies of all unique words in the list, where the key is the word and value is the frequency of that word in the list. While iterating over ...read more

CodingNinjas
author
2y
Using Min Heap

We use a hashmap<key, value> to store the frequencies of all unique words in the list, where the key is the word and value is the frequency of that word in the list. While iterating over...read more

Add answer anonymously...
Atlassian SDE-2 Interview Questions
Stay ahead in your career. Get AmbitionBox app
qr-code
Helping over 1 Crore job seekers every month in choosing their right fit company
65 L+

Reviews

4 L+

Interviews

4 Cr+

Salaries

1 Cr+

Users/Month

Contribute to help millions
Get AmbitionBox app

Made with ❤️ in India. Trademarks belong to their respective owners. All rights reserved © 2024 Info Edge (India) Ltd.

Follow us
  • Youtube
  • Instagram
  • LinkedIn
  • Facebook
  • Twitter