Town Baby Name Chart

MediumheapAlso known as Top K Frequent Words

Every January, a small town's newsletter prints a chart of the most popular baby names from last year. The registry office sends one long list with a name for every baby born, stored in lowercase, like ["mia", "leo", "mia", "ava"].

The chart shows the top k names, most popular first. When two names were given equally often, the editor lists them alphabetically, so nobody can claim the newsletter played favourites.

Your task

Write topNames(names, k). Return the k most frequent names, ordered by how many times they appear (highest first). Names with the same count go in alphabetical order.

Each name appears in the result at most once. k is never more than the number of different names.

topNames(names: string[], k: int) → string[]

Examples

Example 1
Input
names = ["mia", "leo", "mia", "ava", "leo", "mia", "zoe"]
k = 2
Output
["mia", "leo"]
Why

mia appears 3 times, leo 2, ava and zoe once each. The top 2 are mia, then leo.

Example 2
Input
names = ["noah", "eli", "ivy", "eli", "noah", "ivy", "amir"]
k = 3
Output
["eli", "ivy", "noah"]
Why

noah, eli and ivy all appear twice, so they tie and are listed alphabetically: eli, ivy, noah. Listing them in the order they first appear (noah, eli, ivy) would be wrong.

Constraints

  • 1 ≤ names.length ≤ 20,000
  • 1 ≤ k ≤ number of distinct names
  • Names use only lowercase letters a to z, 1 to 15 letters long.
Start with brute force

For each distinct name, count it by scanning the whole list again, then sort. Counting that way is O(n · m) for n babies and m distinct names, up to 400 million steps for 20,000 babies with all-different names.

Counting with a hash map fixes that. After counting, sorting all m names by (count, then name) costs O(m log m), which is fine here. A heap of size k cuts it to O(m log k), which helps when the list of distinct names is huge and the chart is short.

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