Skip to content
Problem 692 · LeetCode 692(opens in a new tab)

Top K Frequent Words

MediumHash tables

Given a list of lowercase strings words, find the k words that show up most often in it.

Order the answer from the most frequent word to the least. When two words appear the same number of times, the one that comes first in alphabetical order goes first.

Example 1

Input:  words = ["red", "blue", "red", "green", "blue", "red"], k = 2
Output: ["red", "blue"]
Why:    red appears 3 times, blue 2, green once
2 more examples and the constraints

Example 2

Input:  words = ["oak", "elm", "fir", "elm", "oak", "ash"], k = 3
Output: ["elm", "oak", "ash"]
Why:    elm and oak tie at 2; ash beats fir alphabetically

Example 3

Input:  words = ["sun"], k = 1
Output: ["sun"]
Why:    the only word is the most frequent one

Constraints

  • 1 ≤ length of words ≤ 500
  • 1 ≤ length of each word ≤ 10, lowercase English letters only
  • 1 ≤ k ≤ number of different words

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. Count, then sort everythingO(n log n)
  2. Count, then a heap of size kO(n log k)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for 500 different words, k = 5Verdict
Count, then sort everythingO(n log n)
Fine; short to write
Count, then a heap of size kO(n log k)
Best; answers the follow-up

n = number of words; k = how many to return.

Edge cases to test

  • A single word. ["sun"] with k = 1 returns ["sun"].
  • Every word appears once. All counts tie, so the answer is the first k words in alphabetical order.
  • k equals the number of different words. Return all of them, sorted by count and then alphabetically.
  • Ties at the cut-off. If two words tie for the last spot, the alphabetically earlier one is kept.

Common mistakes

  • Using the same tie-break inside the min-heap as in the answer, which evicts the alphabetically earlier word.
  • Returning the heap's pop order without reversing it, so the list runs from least to most frequent.
  • Sorting by count only and forgetting the alphabetical tie-break.

How to talk through it

  1. 1Clarify. How are ties broken? Alphabetically. Is k always at most the number of different words?
  2. 2Count first. A hash map from word to count is O(n) and needed by every approach.
  3. 3Give the simple version. Sort the distinct words by (count descending, word ascending) and take k: O(n log n).
  4. 4Answer the follow-up. Keep a min-heap of size k whose top is the weakest word; evict when it grows past k.
  5. 5Test out loud. Run a case where two words tie at the cut-off and check the alphabetically earlier one stays.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?