Town Baby Name Chart

MediumheapAlso known as Top K Frequent Words

Every January, a town newsletter prints the most popular baby names from last year. The registry sends one list with a lowercase name for every baby born, like ["mia", "leo", "mia", "ava"].

The chart shows the top k names, most popular first, with ties listed alphabetically.

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

Count each distinct name by rescanning the whole list, then sort. That is O(n · m) for n babies and m distinct names, up to 400 million steps for 20,000 all-different names.

A hash map fixes the counting. Sorting all m names by (count, then name) is then O(m log m), fine here. A heap of size k cuts it to O(m log k), which helps when there are many distinct names 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