Top K Frequent Words
Real-world version: Most Drawn Part CodesThe statement here is our own: the same inputs, outputs and technique.
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.
def busiest_codes(draws: list[str], k: int) -> list[str]:public List<String> busiestCodes(String[] draws, int k)Checking your plan…
How this problem was checked
- Passed: Reference solution run against 11 test cases: 11 passed
- Passed: 3 worked examples confirmed by running the code
- Passed: 0 eight-word sequences shared with the parent problem's text
- Passed: Agrees with an independent brute-force solution on random inputs
- Passed: Test set shown to catch deliberately broken solutions
- Passed: Reviewed by a separate quality pass
- Passed: Function arity matches the parent problem's