Given a list of items, return the top K most frequent items with their counts. Put higher counts first. When counts tie, put the names in alphabetical order.
Input: One line: K, followed by space-separated item names. Names are case-sensitive words without spaces.
Output: Print up to K item:count pairs separated by spaces. Rank higher counts first and break ties alphabetically.
Input:
2 echo cd echo pwd echo cd
Output:
echo:3 cd:2
Explanation: echo occurs three times, cd twice and pwd once. The two highest counts give echo:3 cd:2.
Input:
2 pwd cd pwd cd ls
Output:
cd:2 pwd:2
Explanation: cd and pwd each occur twice. Break their tie alphabetically, putting cd before pwd; ls is outside the top two.
Input:
1 fast-eval fast-eval fast-eval
Output:
fast-eval:3
Explanation: The only distinct item is fast-eval with count three, so it fills the single requested position.
Input:
5 echo pwd
Output:
echo:1 pwd:1
Explanation: Only two distinct names exist, even though K is five. Both counts are one, so print echo before pwd alphabetically.
Input:
3 run echo which echo run echo which pwd
Output:
echo:3 run:2 which:2
Explanation: echo has count three; run and which each have count two. Rank echo first and break the tie with run before which. pwd is fourth.
Can a map store the counts? Which two values should your sorting rule compare?
A shell can summarize an existing command history with this frequency-counting idea. Level 6 ranks a supplied trace; it does not monitor people or speed up command execution.
System 1: Build a Command-Line Shell
Optional application of the idea. You write the System solution separately.
Start with a command loop, or revisit any coding problem. The System track is optional.
echo:3 cd:2