Top K Frequent Words

MediumBucket Sort · Heap · Trie🧩 Bucket & Counting SortLeetCode #692 ↗Updated

Problem

Given an array of lowercase words and an integer k, return the k words that occur most often. Order the answer by frequency, highest first; words with equal frequency are ordered alphabetically.
Input[i,love,leetcode,i,love,coding], k=2Output[i,love]
Input[a,b,a,c,b,a], k=3Output[a,b,c]

1 ≤ n ≤ 500  ·  1 ≤ word length ≤ 10, lowercase  ·  1 ≤ k ≤ #unique words  ·  Follow-up: O(n log k) time.

Try it yourself

Java
class Solution {
    public List<String> topKFrequent(String[] words, int k) {
        
    }
}
Your code is saved in this browser.Submit on LeetCode ↗
Key insight
Count first; then it is a ranking problem with a two-key order (count desc, word asc). Counts are bounded by n, so words can be bucketed by count; a trie inside each bucket yields its words alphabetically without sorting.
PatternBucket & Counting Sort

Instinct Keys live in a small, known range (letters, frequencies 1..n, bounded values) - index an array by the key instead of comparing, and get O(n).

Memory hack Don't compare, just file it - every value walks straight to its own pigeonhole, then you read the shelves in order.

Open the Bucket & Counting Sort guide →

Approaches

Brute ForceCount + Sort All Unique Words

Time O(n + m log m)Space O(m)

Build a frequency map, then sort the m unique words with a comparator: higher count first, ties broken by compareTo. The first k entries are the answer.

Java
public List<String> topKFrequent(String[] words, int k) {
    Map<String, Integer> count = new HashMap<>();
    for (String w : words) count.merge(w, 1, Integer::sum);
    List<String> cand = new ArrayList<>(count.keySet());
    cand.sort((a, b) -> count.get(a).equals(count.get(b))
            ? a.compareTo(b) : count.get(b) - count.get(a));
    return new ArrayList<>(cand.subList(0, k));
}

Short and clear, but sorts every word even when k is tiny.

At a glance

LevelApproachTimeSpace
Brute ForceCount + Sort All Unique WordsO(n + m log m)O(m)
BetterMin-Heap of Size kO(n + m log k)O(m)
OptimalBucket Sort by Count + Trie per BucketO(n · L)O(n · L)
Common pitfalls
  • Heap tie-break must be reversed (larger word on top) or the wrong word is evicted.
  • Comparing boxed Integers with == — fails above 127.
  • Forgetting to reverse the heap output (it comes out weakest first).
Interview tips
  • State the ordering rule precisely before coding the comparator.
  • Point out k ≤ m, so the heap is O(m log k) ≤ O(m log m).
  • Contrast with Top K Frequent Elements (347), where ties need no ordering.
Pattern
Top-k with bounded keys → size-k min-heap, or bucket sort when the key (a count) is ≤ n.
My notes saved in this browser