Quick revision
The short answer
We count each word with a HashMap using merge(word, 1, Integer::sum), then push the entries through a min-heap that never holds more than k entries, ordered by count and then by word. Whenever the heap grows past k we poll the smallest, so at the end it holds the k most frequent words, which we poll and reverse to get the highest first. The cost is O(n + m log k) time and O(m + k) space for n words and m distinct words.
What to remember
In this answer, we counted words with HashMap.merge, then kept a min-heap of at most k entries ordered by count and, for ties, reverse alphabetical order, polling whenever it grew past k. Because a PriorityQueue does not iterate in sorted order, we polled the heap into a list and reversed it to get the most frequent word first. The cost is O(n + m log k) time and O(m + k) space, and bucket sort by frequency brings it to O(n + m) at the price of an array sized by n.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
We count each word with a HashMap using merge(word, 1, Integer::sum), then push the entries through a min-heap that never holds more than k entries, ordered by count and then by word. Whenever the heap grows past k we poll the smallest, so at the end it holds the k most frequent words, which we poll and reverse to get the highest first. The cost is O(n + m log k) time and O(m + k) space for n words and m distinct words.
Why this question is asked
Top-k problems are everywhere in real systems: the most searched terms, the noisiest log messages, the busiest customers, the hottest cache keys. Interviewers like this question because it checks three things at once: whether we can count efficiently with a map, whether we know the trick of keeping a small heap of size k instead of sorting everything, and whether we understand that a PriorityQueue does not iterate in sorted order. In this answer, we will write the counting step, build the bounded heap and explain why it is a min-heap and not a max-heap, extract the result in the right order, work out the complexity, and finally look at a bucket sort alternative that is linear.
1Counting the Words
The first step is a frequency table. A HashMap<String, Integer> maps each word to how many times we have seen it. The neatest way to update it is Map.merge: if the word is absent, merge stores 1; if it is present, it applies Integer::sum to the old count and 1. That replaces the older pattern of get, check for null, and put, and it does only one hash lookup in HashMap's implementation.
This loop is O(n) for n words, assuming string hashing is cheap relative to the work. The map holds m entries, one per distinct word, so it needs O(m) space. If the input has mixed case or punctuation, this is also where we normalise, for example with toLowerCase(Locale.ROOT).
2Why the Heap Is a Min-Heap of Size k
It feels natural to use a max-heap and poll k times, and that works, but it puts all m entries into the heap, costing O(m log m). The better idea is to keep only the best k candidates seen so far. To decide quickly whether a new entry beats one of them, we need fast access to the weakest of the k, which is exactly what a min-heap gives us at its root.
So we offer every entry into a min-heap ordered by count. Whenever the size exceeds k, we poll, which throws away the entry with the smallest count. The heap never holds more than k + 1 entries, so each offer and poll costs O(log k) rather than O(log m). With m = 1,000,000 distinct words and k = 10, that is about 4 comparisons per operation instead of about 20.
- Take the next (word, count)
- Offer it to the min-heap
O(log k) - Is heap size > k?YesPoll the smallest entryNoKeep it
- More entries?YesBack to the first stepNoHeap holds the top k
4 steps in order. Play them, or step through them one at a time.
3Writing the Method
Now we put it together. The comparator compares counts in ascending order, because this is a min-heap. For ties, the usual requirement is that higher-ranked words come first alphabetically, so the weaker of two equal counts is the word that is later in the alphabet; that means the heap's tie breaker compares words in reverse order. Getting the tie breaker right makes the output deterministic, which matters for tests.
Notice the last step. We cannot just iterate the heap or call new ArrayList<>(heap), because PriorityQueue iterates in array order, which is heap order, not sorted order. Polling gives the entries from weakest to strongest, so we reverse the list at the end. Reversing k items is O(k). Holding HashMap entries in the heap is safe here because we do not modify the map after counting.
4Working Out the Complexity
Counting reads every word once: O(n). The heap loop visits m distinct entries, and each does an offer and at most one poll on a heap of size at most k + 1: O(m log k). Extraction polls k times and reverses: O(k log k), which is smaller than the loop. So the total time is O(n + m log k). Space is O(m) for the map plus O(k) for the heap and the result, so O(m + k).
When k is small, log k is close to a constant and the whole thing is practically linear. When k approaches m, the heap approach becomes O(m log m), the same as sorting all entries, and simply sorting the entry list is just as good and simpler to read.
| Approach | Time | Extra space |
|---|---|---|
| Sort all entries by count | O(n + m log m) | O(m) |
| Max-heap of all entries, poll k | O(n + m + k log m) | O(m) |
| Min-heap bounded to k | O(n + m log k) | O(m + k) |
| Bucket sort by frequency | O(n + m) | O(n + m) |
5The Linear Alternative: Bucket Sort by Frequency
A count can never exceed n, the number of words. So we can create an array of n + 1 buckets, where bucket c holds the words that appeared exactly c times, and then walk the buckets from the highest count down until we have k words. Filling the buckets is O(m) and walking them is O(n), so the whole method is O(n + m).
The catch is memory: the bucket array has n + 1 slots even when only a few counts are used, so for a billion words it is not practical. The heap version works in a streaming fashion and only needs the map and k entries, which is why it is the usual interview answer, with bucket sort mentioned as the linear option.
6Follow-up questions
What if the words do not fit in memory?
Then we cannot hold one HashMap. We partition the words by hash into files or workers so that each word always lands in the same partition, count each partition separately, take the top k of each, and merge those small lists with another heap. If an approximate answer is acceptable, a Count-Min Sketch with a small heap of heavy hitters uses a fixed amount of memory.
Could we use streams instead of a manual loop?
Yes, counting with Collectors.groupingBy(Function.identity(), Collectors.counting()) and then sorting the entry stream by value descending and limiting to k is short and readable. It sorts all m entries, so it costs O(m log m), which is fine for moderate m. The bounded heap is the better answer when m is large and k is small.
Why not keep a TreeMap of count to words?
A TreeMap would also keep things ordered, but every insert is O(log m) on the full set of entries and each node carries more overhead than an array slot in a heap. The bounded min-heap only ever pays for k elements, which is the whole point of the technique.
7Conclusion
In this answer, we counted words with HashMap.merge, then kept a min-heap of at most k entries ordered by count and, for ties, reverse alphabetical order, polling whenever it grew past k. Because a PriorityQueue does not iterate in sorted order, we polled the heap into a list and reversed it to get the most frequent word first. The cost is O(n + m log k) time and O(m + k) space, and bucket sort by frequency brings it to O(n + m) at the price of an array sized by n.
Open with
First I count the words with a HashMap from word to integer, using merge with the word, one and Integer::sum, which is O(n) for n words. Then, instead of sorting all m distinct words, I keep a min-heap of size k.
Then, if they want more
I use a min-heap because I want quick access to the weakest of my current top k: for each entry I offer it to the heap, and if the size goes above k I poll, which throws away the entry with the lowest count.
The comparator orders by count ascending and, for equal counts, by word in reverse so that ties come out alphabetically at the end. Each offer and poll costs log k, so the loop is O(m log k), and the total is O(n plus m log k) time with O(m plus k) space.
One detail matters: I cannot just iterate the PriorityQueue to get the answer, because iteration follows the heap array and is not sorted. So I poll everything into a list, which gives weakest to strongest, and reverse it. If k is close to m, plain sorting is just as good.
And if I want strictly linear time, I can bucket words by frequency in an array of size n plus 1 and walk it from the top, which is O(n plus m) but uses memory proportional to n.
About this answer
- Last updated
- 12 November 2026
- Checked
- Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the official documentation for the version you use. What the checks cover
- Where the question comes from
- Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "Write Java code that returns the k most frequent words from a List<String> using a...": https://scrivio-interview-library.netlify.app/java/algorithms-and-data-structures/4f60a28565/