Problem Statement

Top K Frequent Words

You are given a list of words and a number k. You need to return the k words that show up the most. The most common word comes first, then the next most common, and so on. If two words show up the same number of times, the one that comes first in the alphabet wins. So first we count how many times each word appears, then we pick out the k winners. The two tools that make this easy are a hash map for counting and a heap for grabbing the top k.

mediumHash TableHeapHeap / Priority QueueTime: O(n log k) · Space: O(n)

Signals to notice

find k most frequent wordsfrequency + lexicographic orderingcustom comparison

Brute force first

Count frequencies, sort all words by frequency then alphabetically. It is a fair place to begin because it matches the surface of the question, yet it does not capture the deeper structure that makes the problem simpler.

The key insight

Count frequencies with hash map, use a min-heap of size k with custom comparator (lower frequency first, higher alphabetical first for ties). Instead of recomputing the world every time, you preserve just enough context to let the next decision become obvious.

Trace it on words=["i","love","leetcode","i","love","coding"], k=2

Count freq: i->2, love->2, leetcode->1, coding->1
Build candidates (keys): [i, love, leetcode, coding]
Sort key for each = (-freq, word): i->(-2,'i'), love->(-2,'love'), leetcode->(-1,'leetcode'), coding->(-1,'coding')
Sort ascending by key: (-2,'i') < (-2,'love') < (-1,'coding') < (-1,'leetcode')
Sorted order: [i, love, coding, leetcode]
Take first k=2: [i, love]
Return ["i", "love"]

What must stay true

The min-heap evicts the 'worst' candidate — lowest frequency, or alphabetically later for ties. After processing all words, the heap contains the top k in reverse order. As long as that statement keeps holding, you can trust the steps built on top of it.

Shape of the loop

freq = count occurrences of each word
candidates = keys of freq
sort candidates by key (-freq[word], word)   # freq desc, then word asc
return first k of candidates

Pseudocode only — the full worked solution lives in the Solution tab.

Easy way to go wrong

Wrong tie-breaking in the heap comparator — for equal frequency, the lexicographically LARGER word should be at the top of the min-heap (to be evicted first), keeping the smaller word. When the code becomes mechanical before the idea is clear, small edge cases start breaking the whole story.

Heap / Priority Queue Pattern