Problem 535
Top K Frequent Words
Medium · 20 pts · String, Hash Table, Sorting
Problem
You are given N words and an integer K. Print the K words that appear most often, from the most frequent to the least frequent. Words with the same frequency are ordered alphabetically (lexicographically). K never exceeds the number of different words. Count every word with a hash map, then sort the distinct words by (frequency descending, word ascending) and take the first K.
Input
The first line contains N and K. The second line contains N space-separated lowercase words.
Output
Print the K words separated by spaces.
Constraints
1 <= N <= 100000; 1 <= K <= number of distinct words; 1 <= |word| <= 10
Example input
6 2 i love leetcode i love coding
Example output
i love
Explanation
In i love leetcode i love coding, the words i and love appear twice and the others once. With K = 2 the answer is i love, because i comes before love alphabetically.