Skip to content

Top K Frequent Words

MediumHeap / Priority Queue
Decode it first. Clues, constraints, pattern and plan before any code.

Given a list of words and a number k, return the k most frequent words. Order the result from most frequent to least frequent, and break ties alphabetically (the word that comes first in dictionary order goes first).

words = ["i", "love", "code", "i", "love", "tea"], k = 2  →  ["i", "love"]
words = ["cat", "bat", "cat", "bat", "ant"],         k = 2  →  ["bat", "cat"]

In the second example bat and cat both appear twice, and bat comes first alphabetically. Can you do it in O(n log k)?

Constraints

  • 1 <= words.length <= 500
  • 1 <= words[i].length <= 10
  • words[i] holds only lowercase English letters.
  • 1 <= k <= the number of distinct words.