Bakery Bestsellers

Mediumhash mapAlso known as Top K Frequent Elements

You run a small bakery, and the till keeps a log with one line per item sold: croissant, scone, croissant, bagel, and so on. The front window only has room for a few trays.

Before tomorrow you want to know which items sold the most today, so they get the window. You do not care how they are ranked among themselves, only which ones make the cut.

Your task

Write bestsellers(sales, k). Return the k items that appear most often in sales, in any order, each item once.

The input is chosen so the answer is unique: the k-th best item always sold strictly more than the item in place k + 1.

bestsellers(sales: string[], k: int) → string[] Any order of the returned list is accepted.

Examples

Example 1
Input
sales = ["scone", "croissant", "bagel", "croissant", "scone", "croissant", "muffin"]
k = 2
Output
["croissant", "scone"]
Why

Counts: croissant 3, scone 2, bagel 1, muffin 1. The two bestsellers are croissant and scone. Returning ["scone", "croissant"] is just as correct.

Example 2
Input
sales = ["bagel", "bagel", "eclair", "donut", "donut", "donut"]
k = 1
Output
["donut"]
Why

Donut sold 3, bagel 2, eclair 1. Bagel was sold first, but donut sold the most.

Constraints

  • 1 ≤ sales.length ≤ 100,000
  • 1 ≤ k ≤ number of different items in sales
  • Item names are non-empty lowercase strings.
  • The set of the k most sold items is unique.
Start with brute force

Take each different item, count it by scanning the whole log, and then repeatedly pick the item with the largest count that you have not picked yet.

Counting each item by rescanning costs O(n) per item, so O(n · m) for m different items. With 100,000 sales and thousands of items that is hundreds of millions of steps. Counting once with a map, then sorting the m items by count, gets you to O(n + m log m), which is fine. Buckets remove even the sort.

Hints

0 of 4 shown

Walkthrough and solution

Unlocks when you pass every test. Stuck for a while? Looking is fine too, as long as you then close it and write the code yourself.

Ctrl+Enter runs

Run your code to see results here. Run checks the examples. Submit checks every test, including hidden edge cases.

Write code