Visualize

Pattern visualizer

Top K Frequent Words

The insight is the same as any top-k-by-frequency problem: cap a heap at size k so it only ever holds the strongest k candidates seen so far, evicting the weakest one whenever a stronger candidate arrives — that avoids sorting every distinct word just to find a handful of them. Here "weakest" means lowest frequency first, with alphabetically-later words treated as weaker on a tie, so when two words are equally frequent the one earlier in the alphabet is favored both when the heap has to evict and when the final answer is ordered. Animated on: Find the k most frequent words, breaking ties by alphabetical order.

Min-heap with lexical tie-break

time O(n log k)space O(k)step 1 / 12
i
[0]
love
[1]
leetcode
[2]
i
[3]
love
[4]
coding
[5]
line 3

Process words[0]="i" (1st occurrence). Count map: {i:1}. Highlight current word at index 0.

Pseudocode
1FUNCTION topKFrequentWords(words, k):
2 cnt = a lookup table (wordits count)
3 FOR each word w in words: add one to cnt[w]
4 h = a min-heap keyed by count, ties broken alphabetically (weakest on top)
5 FOR each word w in cnt:
6 push (count of w, word w) onto the heap
7 IF heap size > k: pop the weakest (the min)
8 END FOR
9 RETURN the words left in the heap, sorted
10END FUNCTION

← / → step · space play · Home restart

Where to practice Heap