Show problems as
Classic problem #692MediumArrayHash TableStringTrieSortingHeap (Priority Queue)Bucket SortCounting

Top K Frequent Words

Real-world version: Most Drawn Part Codes
Tracked in this browser only
Read Top K Frequent Words on LeetCode(opens in a new tab)

The statement here is our own: the same inputs, outputs and technique.

Learn the pattern firstTop K Frequent Elements · Priority Queues, animated step by step

A repair bay logs the code of every part it lifts off the shelf. The log arrives as draws, the part codes in the order they were lifted, one entry per part, so a code drawn four times appears four times.

Return the k codes drawn the most, listed from the most drawn down to the least drawn among them.

Codes drawn the same number of times are listed in dictionary order, which keeps the answer unambiguous. Dictionary order compares two codes letter by letter from the front and settles them at the first letter that differs; when one code is a prefix of the other, the shorter code comes first.

Examples

Example 1

Input
draws = ["ratchet", "clamp", "ratchet", "shim", "clamp", "ratchet"], k = 2
Output
["ratchet", "clamp"]

The bay drew ratchet three times, clamp twice and shim once, so the two most drawn codes are ratchet then clamp.

Example 2

Input
draws = ["shim", "bolt", "shim", "bolt", "nut"], k = 2
Output
["bolt", "shim"]

Both shim and bolt were drawn twice, so they are listed in dictionary order, which puts bolt first; nut was drawn once and misses out.

Example 3

Input
draws = ["ab", "b", "ab", "b", "cd"], k = 3
Output
["ab", "b", "cd"]

Codes ab and b were each drawn twice and ab is earlier in dictionary order, since a comes before b at the first letter. Code cd was drawn once and takes the last place.

Constraints

  • 1 <= draws.length <= 500
  • 1 <= draws[i].length <= 10
  • draws[i] consists of lowercase English letters
  • 1 <= k <= the number of distinct codes in draws

The signature

The editor starts with this. It matches the parent problem's shape, so a solution that works here works on a standard judge unchanged.

Python
def busiest_codes(draws: list[str], k: int) -> list[str]:
Java
public List<String> busiestCodes(String[] draws, int k)