Problem title
Difficulty
Avg time to solve

Point to Greatest Value Node
Easy
10 mins
Diagonal Traversal
Moderate
15 mins
Sub Query Sum
Easy
10 mins
Check if the Word is present in Sentence or not
Easy
15 mins
Create Sequence
Easy
10 mins
Closest Binary Search Tree Value
Easy
15 mins
Add One to Linked List
Easy
10 mins
Exactly One Child
Easy
15 mins
Predecessor and Successor In BST
Moderate
25 mins
Pair sum in a BST
Easy
15 mins
8

K Most Frequent Words

Difficulty: MEDIUM
Contributed By
Ashwani |Level 1
Avg. time to solve
36 min
Success Rate
65%

Problem Statement

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
Sample Input 1:
6 2
i love codingninjas i love coding
Sample Output 1:
i love
Sample Input 2:
8 3
the sky is blue the weather is hot
Sample Output 2:
is the blue
Explanation for Sample Input 2:
“is” and “the” are words with a frequency of 2.
“sky”, “blue”, “weather”, and “hot” are the words with a frequency of 1.

The words with a frequency of 2 are the most frequent words and the lexicographically smallest word from the words with a frequency of 1 is “blue”.
Reset Code
Full screen
copy-code
Console