Skip to content
Decoder

Top K Frequent Words

Medium

Problem

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).

Example 1

Input
words = ["i", "love", "code", "i", "love", "tea"], k = 2
Output
["i", "love"]

Example 2

Input
words = ["cat", "bat", "cat", "bat", "ant"], k = 2
Output
["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.

Read it once before you touch anything

Want some pressure? Start the timer. In an interview you get about two minutes to understand the problem.

  1. 1Read the goalWhat goes in, what comes out
  2. 2Scan the examplesCheck one by hand
  3. 3Note the constraintsThey set your Big O
Say what it asks in one sentence
Say it out loud first, then compare with ours.