#C8656. Top K Frequent Words
Top K Frequent Words
Top K Frequent Words
You are given a list of words and an integer k. Your task is to find the k most frequent words in the list. The words must be sorted in descending order by their frequency. If two words have the same frequency, they should be sorted in lexicographical (alphabetical) order in ascending order.
For example, if the input list is ["apple", "banana", "apple", "orange", "banana", "apple"]
with k = 2
, the answer is ["apple", "banana"]
.
Note: If any formulas are needed, they must be written in LaTeX format (e.g., $f(x)=\ldots$
).
inputFormat
The input is given via stdin and has the following format:
- The first line contains two integers,
n
andk
, wheren
is the number of words. - The second line contains
n
words separated by spaces.
outputFormat
Output the k most frequent words, each on a separate line, in order. The words are sorted first by descending frequency, and then lexicographically in ascending order when frequencies tie.
## sample6 2
apple banana apple orange banana apple
apple
banana
</p>