Bakery Bestsellers

Mediumhash mapAlso known as Top K Frequent Elements

Your bakery's till logs one line per item sold: croissant, scone, croissant, bagel, and so on. The front window has room for only a few trays.

Tomorrow, today's best sellers get the window. Their ranking among themselves does not matter, 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

Croissant sold 3, scone 2, bagel 1 and muffin 1, so the top two are croissant and scone; ["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

Count each different item by scanning the whole log, then repeatedly pick the unpicked item with the largest count.

Rescanning costs O(n) per item, so O(n · m) for m different items: hundreds of millions of steps with 100,000 sales and thousands of items. Counting once with a map and sorting the m items gives 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