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
Process words[0]="i" (1st occurrence). Count map: {i:1}. Highlight current word at index 0.
1FUNCTION topKFrequentWords(words, k):2 cnt = a lookup table (word → its 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 heap7 IF heap size > k: pop the weakest (the min)8 END FOR9 RETURN the words left in the heap, sorted10END FUNCTION
← / → step · space play · Home restart