Top K Frequent Words

Practice this coding question on Coding Gurukul.

Problem statement

A reading club collects keyword cards after its weekly meetings. The same keyword can appear on many cards, and the organizer wants a short report containing only the k most frequent distinct keywords. Ties must be resolved consistently so every organizer produces the same report. Your task Count all occurrences of each word. Return exactly k distinct words, ordered by decreasing frequency. When two words have the same frequency, the lexicographically smaller word comes first. All words use lowercase English letters, so normal alphabetic comparison applies; a word precedes a longer word for which it is a prefix. Repeated cards increase a word’s frequency but do not create duplicate report entries. The value k never exceeds the number of distinct words. A frequency map followed by a heap or sorting can determine the report. Worked example For cards [pear, apple, pear, plum, apple, pear] and k=2, pear appears three times and apple twice. Print pear apple. If apple and pear both appeared twice, apple would come first because of the tie rule.

Input format

First line: n k. Next n whitespace-separated lowercase words.

Output format

Print k words separated by single spaces, in the required ranking order.

Constraints

1 <= n <= 500; 1 <= word length <= 10; 1 <= k <= number of distinct words.

Sample input

6 2
pear apple pear plum apple pear

Sample output

pear apple

Sign in to run or submit a solution in C++, Java or Python.

Loading Coding Gurukul…