iq.lab
Python starts when a code cell comes near or you run one
mediumHeapsHash maps and sets target 25 min

Most searched words

You get a list words from a search log, one word per search, and an integer k. Return the k words that were searched most often, as a list ordered from most searched to least.

When two words were searched the same number of times, the one that comes first alphabetically goes first. Alphabetical order here is the order Python's < gives for strings, so "ab" comes before "abc".

k is at least 1 and at most the number of different words.

Example 1
Inputwords = ["sql", "join", "sql", "index", "join", "sql"], k = 2Output["sql", "join"]

"sql" was searched 3 times, "join" 2 times and "index" once.

Example 2
Inputwords = ["map", "heap", "trie", "heap", "map", "set"], k = 3Output["heap", "map", "set"]

"heap" and "map" tie at 2, and "heap" comes first alphabetically. "set" and "trie" tie at 1 and only one fits: "set" comes first.

Constraints
  • 1 ≤ len(words) ≤ 105

  • Each word has 1 to 10 lowercase English letters.

  • 1 ≤ k ≤ the number of different words

Plan it first

Write a line for each before you code, then say them out loud. Compare with the Approach tab afterwards.

⌘+Enter runs 0:00Python starts when a code cell comes near or you run one
Run examples checks the examples. Submit runs every test, including edge cases and, when the problem has one, a speed check on a large input.