Community Problem

Top K Frequent Words

Difficulty: Medium

Return the k most frequent words, breaking frequency ties alphabetically and returning results in descending frequency.

Top K Frequent Words

Return the k most frequent words, breaking frequency ties alphabetically and returning results in descending frequency.

MEDIUM
Free
heap
priority-queue
hash-table
sorting

By CodeSnatch

April 18, 2026

·

Updated May 18, 2026

262 views

8

4.5 (15)

I see this problem rejected as "easy, just sort" by mid-level engineers, then watch them stumble on the tie-break in the 30-second window after a senior interviewer asks the follow-up. The full version of the problem (O(n log k) with a min-heap of size k) requires a comparator that breaks frequency ties alphabetically, which means the ordering inside the heap is non-trivial: less frequent loses, and on a frequency tie, the larger string loses. The catalog covers Top K Frequent Elements (numeric) but skipped this string variant where the tie-break is the whole interview signal.

Top K Frequent Words

Given an array of strings words and an integer k, return the k most frequent strings.

Return the answer sorted by frequency from highest to lowest. Sort the words with the same frequency by their lexicographical order (ascending).

Examples

Example 1:

  • Input: words = ["i", "love", "leetcode", "i", "love", "coding"], k = 2
  • Output: ["i", "love"]
  • Explanation: "i" and "love" are the two most frequent words. Both appear twice. The tie is broken by lexicographical order: "i" < "love".

Example 2:

  • Input: words = ["the", "day", "is", "sunny", "the", "the", "the", "sunny", "is", "is", "day"], k = 4
  • Output: ["the", "is", "day", "sunny"]
  • Explanation: Frequencies are the=4, is=3, sunny=2, day=2. The top two are unambiguous. day and sunny tie at frequency 2, and the tie-break is lex ASCENDING, so day comes before sunny.

Example 3:

  • Input: words = ["hello"], k = 1
  • Output: ["hello"]
  • Explanation: Single word, single result.

Example 4:

  • Input: words = ["a", "aa", "aaa"], k = 1
  • Output: ["a"]
  • Explanation: All three frequencies are 1. The one with the smallest lexicographical order wins.

Constraints

  • 1 <= words.length <= 500.
  • 1 <= words[i].length <= 10.
  • words[i] consists of lowercase English letters.
  • k is in the range [1, number of unique words[i]].

Follow-up

The naive approach is to sort all unique words by (frequency desc, word asc) in O(u log u) where u is the unique-word count. Can you do it in O(u log k) with a min-heap of size k? You will need a comparator that pops the "least good" item: the one with the smallest frequency or, on a tie, the lexicographically LARGEST word.

Solution

Hints

0/4
Hint 1
Hint 2
Hint 3
Hint 4
All Problems