Ctrl K

Most Searched Words

Medium
You get a log of search queries queries, each a single word, and an integer k. Return the k words that appear in the log most often. Order the answer by frequency, highest first. Words with the same frequency go in alphabetical order. Try to fit into O(n log k) time and O(n) extra space.
Example 1
queries=["tea", "cake", "tea", "jam", "cake", "tea", "bun"], k=3 → ['tea', 'cake', 'bun']

"tea" appears 3 times, "cake" twice, "bun" and "jam" once each. Of the last two, "bun" comes first alphabetically.

Example 2
queries=["red", "blue", "red", "blue", "green"], k=2 → ['blue', 'red']

"red" and "blue" both appear twice, so alphabetical order decides between them.

Constraints
  • 1 ≤ len(queries) ≤ 500
  • 1 ≤ len(queries[i]) ≤ 10
  • queries[i] consists of lowercase English letters
  • 1 ≤ k ≤ the number of distinct words in queries
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsMost Common Values MediumCharacters Grouped by Count MediumJobs With a Cooldown MediumWord Grown Letter by Letter MediumNo Twin Letters Side by Side Medium
loading Python…
Input
queries=["tea", "cake", "tea", "jam", "cake", "tea", "bun"], k=3
Expected
['tea', 'cake', 'bun']

Run checks the first 3 tests in your browser. Submit checks all 91 tests on the server, hidden ones included.