#K88242. Top K Frequent Words

    ID: 37265 Type: Default 1000ms 256MiB

Top K Frequent Words

Top K Frequent Words

Given a list of words, your task is to find the top \(k\) most frequent words in the list. The words should be sorted primarily by their frequency in descending order. If multiple words have the same frequency, they should be sorted in lexicographical order (i.e., alphabetically).

The frequency ordering can be mathematically represented as sorting by \(-f(w)\) where \(f(w)\) is the frequency of word \(w\), and then by the word itself in ascending order.

Input Format: The input is given via standard input. The first line contains two integers \(n\) and \(k\), where \(n\) is the number of words in the list. The second line contains \(n\) words separated by spaces.

Output Format: Output the top \(k\) words on a single line, separated by a space, following the criteria described above.

inputFormat

The first line contains two integers \(n\) (the number of words) and \(k\) (the number of top frequent words to output). The second line contains \(n\) words separated by spaces.

Constraints: \(1 \leq k \leq n \leq 10^5\) (for example).

outputFormat

Output a single line with the top \(k\) words sorted by their frequency (highest first). If multiple words have the same frequency, they should be ordered alphabetically. The words must be separated by a single space.

## sample
7 2
hello world hello my name hello world
hello world