Quick revision
The short answer
Keep a min-heap PriorityQueue<Long> that never holds more than k = 10 values. For each input value, offer it while the heap has fewer than 10 elements; after that, if the value is larger than peek(), the smallest of the current top 10, poll and offer it. The cost is O(n log k) time and O(k) memory, and at the end we poll the heap out and reverse it to get the 10 values in descending order.
What to remember
In this answer, we found the 10 largest values with a single pass and a min-heap of size 10. Each value is offered while the heap is filling, and afterwards replaces the root only if it is larger than peek(), the smallest of the current winners. That gives O(n log k) time, effectively linear for k = 10, and O(k) memory, instead of the O(n) memory needed by sorting or a max-heap of all values. At the end we poll the heap empty and reverse the list for descending order.
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.
Keep a min-heap PriorityQueue<Long> that never holds more than k = 10 values. For each input value, offer it while the heap has fewer than 10 elements; after that, if the value is larger than peek(), the smallest of the current top 10, poll and offer it. The cost is O(n log k) time and O(k) memory, and at the end we poll the heap out and reverse it to get the 10 values in descending order.
Why this question is asked
Top-k questions appear everywhere in real systems: the ten slowest requests, the hundred biggest customers, the most frequent error codes. With hundreds of millions of values, sorting everything wastes time and, worse, needs all values in memory at once, which can be several gigabytes of boxed Longs. Interviewers like this question because the efficient answer needs a small but non-obvious idea: to keep the largest values, we use a min-heap. In this answer, we will see why sorting is the wrong tool, understand why the heap must be a min-heap, write the method, trace it on a small input, work out its complexity, and look at a few practical details.
1Why Not Sort Everything?
The simplest solution is to collect all values into a list, sort it in descending order and take the first ten. That costs O(n log n) time, and with n = 500 million, log2(n) is about 29, so roughly 14.5 billion comparisons. More importantly, it needs all n values in memory at once. A boxed Long takes 16 bytes plus a 4- to 8-byte reference in the list, so 500 million values need around 10 GB of heap.
The input is an Iterable, which hints that the values may be streamed from a file, a database cursor or a network source, and never exist all together. So the real requirement is a single pass with memory that does not grow with n.
2The Idea: A Min-Heap of Size k
We keep a small collection holding the 10 largest values seen so far. For every new value, the only question is whether it belongs in that collection, and that depends on one number: the smallest of the current top 10. If the new value is larger than that smallest one, it replaces it; otherwise it cannot be in the top 10, because there are already ten values larger than it.
So we need a structure that tells us the smallest of the kept values instantly and lets us replace it cheaply. That is exactly a min-heap: peek gives the smallest in O(1), and poll plus offer replace it in O(log k). This is the part that confuses people at first. To keep the largest values, we use a min-heap, because the smallest of the winners is the one at risk of being pushed out.
- Does the heap hold fewer than 10 values?Yesoffer(v) and move onNoCompare with the smallest kept value
- Is v > heap.peek()?Yespoll() the smallest, then offer(v)NoSkip v: it cannot be in the top 10
- Heap still holds exactly the 10 largest so farthe smallest of them sits at the root
3 steps in order. Play them, or step through them one at a time.
3Writing the Method
Here is the method, written for any k so it is easy to test with small values.
Notice the strict comparison v > heap.peek(). A value equal to the smallest kept value does not change the top 10's values, so skipping it saves work. Notice also that the heap is created with initial capacity k, so it never grows during the run.
At the end the heap contains the top k, but in heap order, which is not sorted. Polling repeatedly gives them in ascending order, from the smallest of the winners to the largest, so we reverse the list to return the largest first.
4Tracing It on a Small Input
Let us run it with k = 3 on the values 5, 1, 9, 3, 7, 8 and watch the heap.
At every step the heap holds the three largest values seen so far, and the root is the threshold a new value must beat. Notice how the threshold only rises; as the pass goes on, more and more values are rejected with a single comparison.
5Working Out the Complexity
Each value costs at most one peek, which is O(1), and possibly one poll and one offer on a heap of size k, which are O(log k) each. So the whole pass is O(n log k). With k = 10, log2(k) is about 3.3, so the work is a small constant per value, essentially linear in n. In practice it is even better: on randomly ordered data, the threshold quickly rises and most values are rejected by the first comparison, so the heap is modified only a tiny number of times.
Memory is O(k): ten Longs, whatever n is. That is the decisive advantage. The alternative of putting everything into a max-heap and polling ten times also gives the right answer, but it stores all n values, which is O(n) memory, about the same 10 GB as sorting, and building it costs O(n) time with heapify or O(n log n) with offers.
| Approach | Time | Memory |
|---|---|---|
| Sort everything, take 10 | O(n log n) | O(n): all values held |
| Max-heap of all values, poll 10 | O(n) build + O(k log n) | O(n): all values held |
| Min-heap of size k | O(n log k) | O(k): ten values |
6Practical Details Worth Mentioning
The method unboxes each Long for the comparison, which is cheap but not free. If the source can deliver primitives, such as a LongStream or a long array, a hand-written heap over a long array of size k avoids boxing completely. For k = 10, even a simple sorted array of ten longs with insertion works well, since insertion into ten slots is trivial.
Streams look tempting, for example values.stream().sorted(reverseOrder()).limit(10), but sorted needs to see every element before it can emit the first one, so it typically buffers the whole input; check your JDK version rather than assuming it is optimized. If the input is split across machines or threads, each part computes its own top 10 and a final step merges them, since the global top 10 must be among the local top 10s.
7Follow-up questions
Why a min-heap rather than a max-heap?
Because the decision for each new value depends on the smallest of the values we are keeping. A min-heap puts that value at the root, so the check is a peek and the replacement is a poll plus an offer. A max-heap would put the largest winner at the root, which is the one value we never want to remove.
How would you get the 10 smallest values instead?
Mirror the logic: keep a max-heap of size k, created with Comparator.reverseOrder(), and replace the root when a new value is smaller than peek(). The root is then the largest of the kept small values, the one at risk of being pushed out.
How would this change for the top 10 most frequent items?
First count frequencies with a HashMap from item to count, then run the same size-k min-heap over the map entries, comparing by count. If the number of distinct items is too large to count exactly, approximate structures such as a count-min sketch with a heap of candidates are used.
8Conclusion
In this answer, we found the 10 largest values with a single pass and a min-heap of size 10. Each value is offered while the heap is filling, and afterwards replaces the root only if it is larger than peek(), the smallest of the current winners. That gives O(n log k) time, effectively linear for k = 10, and O(k) memory, instead of the O(n) memory needed by sorting or a max-heap of all values. At the end we poll the heap empty and reverse the list for descending order.
Open with
I would solve it in one pass with a min-heap PriorityQueue of Long that never holds more than k equals 10 elements. The key insight is that to keep the largest values I need quick access to the smallest of the ones I am keeping, because that is the one a new value has to beat.
Then, if they want more
So for each value, if the heap has fewer than ten elements I just offer it. Otherwise I compare it with peek: if it is larger than the current smallest winner, I poll that one out and offer the new value; if not, I skip it, because there are already ten larger values.
Each step is a peek, which is constant time, plus at most a poll and an offer on a heap of size k, so the total is O(n log k), which for k equals 10 is essentially linear, and on random data most values are rejected after one comparison.
Memory is O(k), just ten values, which is the real win here, because sorting or putting everything into a max-heap would need all several hundred million values in memory, around ten gigabytes of boxed Longs, and sorting would be O(n log n).
At the end the heap holds the top ten in heap order, so I poll them out, which gives ascending order, and reverse the list to return them largest first. If boxing mattered I would use a small primitive array instead.
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 documentation below. What the checks cover
- Where the question comes from
- Written by Scrivio for practice. It is not taken from an interview.
- Official documentation
- The Collections Framework, overview, java.util, package documentation
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 a method that returns the 10 largest values from an Iterable<Long> of hundreds of...": https://scrivio-interview-library.netlify.app/java/queues-and-deques/3fee4eea14/