Top K Frequent Words
Problem Statement
You get a list of lowercase words words and a number k. Return the k words that appear the most often.
Sort the answer from the most frequent word to the least frequent. If two words appear the same number of times, the one that comes first alphabetically goes first.
A list of words words, and an integer k.
A list of the k most frequent words. Highest count first; words with equal counts in alphabetical order.
i and love each appear twice. Their counts tie, and i comes first alphabetically.
the appears 4 times, is 3 times, sunny 2 times and day once. The counts are all different, so the order is by count alone.
- • 1 ≤ words.length ≤ 500
- • 1 ≤ words[i].length ≤ 10
- • `words[i]` consists of lowercase English letters.
- • 1 ≤ k ≤ the number of unique words
- • Follow-up: can you solve it in O(n log k) time and O(n) extra space?
Pattern Recognition Clues
Recognising these key signals in the problem description immediately identifies the pattern:
Approach Complexity Ladder
Count the words, sort all (count, word) pairs by count high-to-low then word A-to-Z, take the first k
Count the words; keep a min-heap of at most k (count, word) pairs whose top is the worst; reverse at the end
Count each word with a hash map. Then sort all the distinct words: higher count first, and for equal counts, the alphabetically smaller word first. The first k words are the answer, already in the right order.
Recognition rule for this sub-pattern:
Unlock Complete Visual Walkthrough & Optimal C++
The interactive animated dry-run player, optimized C++ implementation, state invariant derivations, and edge-case breakdown for this question are part of Brute2Best Pro. The anchor question of every sub-pattern is completely free.
First anchor question per pattern, Part 1 LLD & Module 1 C++ basics are 100% Free forever.
How this concept connects to System Design & C++ Systems
Top engineering interviews test whether you understand how algorithms like Heap — Top K translate into production architectures and low-level memory mechanics.