#C13096. Most Common Words
Most Common Words
Most Common Words
You are given a string of text and an integer n. Your task is to extract all words from the text where a word is defined as a contiguous sequence of alphabetic characters (i.e., letters A-Z and a-z). The comparison is case-insensitive.
After extracting all valid words, count the frequency of each word. Then, sort the words primarily in descending order of frequency and secondarily in ascending alphabetical order (i.e. if the frequencies are equal). Finally, output the first n words based on the sorted order.
Mathematically, if f(w) denotes the frequency of a word w, you should sort the words by the tuple \[ (-f(w), w) \] in lexicographical order.
Note: If the total number of distinct words is less than n, then output all the words.
inputFormat
The input is given via standard input (stdin) and consists of two lines:
- The first line contains the text (a string) which may include punctuation, spaces, and mixed-case letters.
- The second line contains an integer n.
outputFormat
The output should be printed to standard output (stdout) as a single line containing the n most common words from the text separated by a single space.
## sampleHello world! Hello, how are you doing in this world?
2
hello world