Loading...
Loading...
An online store logs one word for every product ordered today. The manager wants the k most popular products.
Print k lines, each with a product and how many times it was ordered. A higher count comes first. When two snacks have the same count, the one that comes first in alphabetical order comes first.
Example 1
Input
8 2 bag candle bag cable candle bag laptop cable
Output
bag 3 cable 2
bag has 3 orders. cable and candle both have 2, and cable comes first in alphabetical order.
Example 2
Input
5 3 webcam pen webcam stand pen
Output
pen 2 webcam 2 stand 1
webcam and pen tie at 2, so pen comes first. stand has 1.
Try the problem first. Open one hint at a time.
First count how many times each word appears. A HashMap does this in one pass.
Then you need the k "best" words, where better means a higher count, or the same count and an earlier alphabetical place.
Write that rule as a comparator and give it to a PriorityQueue. The best word stays on top.
Remove from the heap k times and print each word with its count.
Write your Java code, run it on the examples and submit it to hidden tests.
Solve in the editor