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
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
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
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
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
Top Atlassian SDE-2 interview questions & answers
Popular interview questions of SDE-2
Reviews
Interviews
Salaries
Users/Month