Dsa
Heap
Easy
Top K Frequent Words
You are given a list of words. Your task is to return the top K most frequent words in the list. If two words have the same frequency, sort them alphabetically. Print the results as a space-separated string of words.
Input format:
The first line contains integers K (1 <= K <= 100) and N (1 <= N <= 10000), the number of most frequent words to find and the total number of words.
The next N lines each contain a single word, which consists only of lowercase alphabetic characters.
Output format:
Print a single line containing the top K frequent words, sorted by their frequency and then alphabetically, separated by spaces.
Example:
Input:
2 6
banana
apple
banana
orange
apple
banana
Output:
apple banana
Key concepts
heapfrequencystrings
Practise this out loud — free
Start a mock interview on THIS exact question — a voice AI interviewer opens with it, pushes back like a real onsite, then hands you an instant scorecard.
🎙 Practise this question now