Quick revision
The short answer
Finding the k-th largest element is a heaps and top k problem. We keep a min-heap holding the k largest values seen so far; a new value enters only if it beats the heap's smallest, which is then removed, so after one pass the heap's smallest value is the k-th largest overall. It takes O(n log k) time and O(k) space, and quickselect can bring the average time down to O(n).
The solution
What it costs
| Approach | Time | Extra space | Works on a stream? |
|---|---|---|---|
| Sort a copy (brute force) | O(n log n) | O(n) | no |
| Find and remove the maximum k times | O(n k) | O(n) | no |
| Min-heap of size k | O(n log k) | O(k) | yes |
| Quickselect | O(n) average, O(n^2) worst | O(1), changes the array | no |
What to remember
We found the k-th largest element by keeping only the k largest values seen so far in a min-heap, comparing each new value with the heap's root, the weakest of the top k, and replacing the root only when the newcomer beats it. At the end the root is the answer, after O(n log k) time with O(k) space. The clue to remember is the phrase k-th largest, or any top k wording: only k values matter, so keep a heap of size k whose root is the one to throw out first.
1What the k-th largest element means
Imagine a talent show with three chairs on the stage for the finalists. Contestants perform one at a time. While a chair is empty, each performer simply takes one. Once all three are filled, a new performer joins the finalists only by beating the weakest finalist on stage, who then gives up the chair. The judges compare a newcomer only with the weakest finalist. When the show ends, the weakest of the three finalists is the third best performer of the whole evening.
Our question is that show with numbers. We are given an unsorted array of integers and a number k, and we must return the value that would stand in position k if the array were sorted from largest to smallest.
Let us keep one example for the whole article: the array [7, 2, 9, 4, 9, 1] with k = 3. Sorting it from largest to smallest gives 9, 9, 7, 4, 2, 1. The first largest is 9, the second is the other 9, and the third is 7. So the answer is 7. Notice that the two 9s count as two separate values; we are asked for a position, not for distinct values.
Now do it the talent show way by hand. 7 takes a chair, 2 takes a chair, 9 takes the last chair. Then 4 arrives; the weakest finalist is 2, and 4 beats it, so 2 leaves. Then 9 arrives; the weakest is now 4, so 4 leaves. Finally 1 arrives and cannot beat the weakest, 7. The finalists are 7, 9 and 9, and the weakest of them, 7, is the answer.
The two 9s are the first and second largest, and 7 is the third largest, the answer for k = 3.
- k
- 3
- largest first
- 9 9 7 4 2 1
- answer
- 7
1Sorted from largest to smallest the values are 9, 9, 7, 4, 2, 1, so for k = 3 the answer is 7. In the original, unsorted array that 7 sits at index 0.
What to assume
- Do repeated values count separately?
- Yes, as in the example.
- Is k always between 1 and the length of the array?
- We assume so, and throw an exception otherwise.
- May we change the input array?
- We assume not.
A careful candidate asks a few questions first. Do repeated values count separately? Yes, as in the example; finding the k-th largest distinct value is a variant. Is k always between 1 and the length of the array? We assume so, and throw an exception otherwise. May we change the input array? We assume not. Might the values arrive one at a time, as a stream? The heap method handles that without change.
Your turn
Solve it before you read on. Above is one example with the result expected for it. Under What to assume are the points this solution takes as given. Say your approach aloud or type it below, and write the code in your own editor. Then take one hint at a time and compare.
2How to recognise a top k problem
A beginner usually thinks of sorting first, and that is sensible: in a sorted array the answer sits at a known position. It is the brute force we will write next. But a few words in the question suggest we can do less than a full sort, so let us take the clues one at a time.
The first clue is the word k-th, together with largest. The answer depends only on the k largest values. Everything smaller than them could be in any order, or even thrown away, and the answer would not change. In our example the order of 1, 2 and 4 among themselves does not matter at all.
The second clue is the word unsorted. There is no order to lean on, so we will have to look at every value at least once. The real question is how much we must remember while we look.
The third clue is that we want one element, a single value at a position, not the whole sorted list. That is a strong sign that putting all n values in order is more than the question asks for.
Together these clues point to the heaps and top k family of patterns. A heap is a structure that keeps its smallest value, or in another kind its largest, at the top, where we can read it at once. In a min-heap that top value, called the root, is the smallest. Top k means keeping only the best k values seen so far. The general rule to carry to new problems is that whenever a question says the k largest, k smallest, k most frequent, k closest, or the k-th of any of these, we keep a heap of size k whose root is the weakest member, the one to throw out first.
Other approaches look possible. Sorting answers the question but orders all n values. Putting all n values in a max-heap and removing the top k times works too, but stores every value. Quickselect, which splits the array around a chosen value as quicksort does but then works on only one side, is faster on average, and we discuss it in a follow-up.
3The honest first attempt, sorting everything
The brute force is to sort a copy of the array from smallest to largest and read the value k places from the end. We sort a copy so that the caller's array is left as it was. It is obviously correct, and in many programs it would be the right choice.
The first frame is the copy before sorting. In the second, the answer is read at index n - k.
- n
- 6
- k
- 3
1We start from a copy of the array, [7, 2, 9, 4, 9, 1], so that sorting does not change the caller's data.
- n
- 6
- k
- 3
- answer
- copy[3] = 7
2After sorting, the copy is [1, 2, 4, 7, 9, 9]. The third largest is 3 places from the end, at index 6 - 3 = 3, which holds 7.
Let us count. Java sorts an array of n numbers in about n times log2 of n comparisons, so for our six values about 6 times 2.6, roughly 16 comparisons. For n values the time is O(n log n), read as order n log n, and the copy takes O(n) extra memory, which we call the space. Finding and removing the maximum k times costs O(n times k), worse when k is large.
Where is the waste? Look at the second frame. To read one value at index 3, the sort carefully put 1, 2 and 4 in order among themselves, though none of them could ever be the answer. For a million values and k = 10, the sort orders a million values when only the ten largest matter.
So let us ask the question that leads further. While we walk through the array, how many values do we really need to keep in mind? The talent show already told us: only k of them, the best k so far.
4Getting to the heap of size k, one observation at a time
The first observation is about what to remember. Any value that already has k larger values above it can never be the k-th largest at the end, because more values can only push it further down. So at every moment only the k largest values seen so far are still candidates. Those are our three finalists.
The second observation is about what we do with a new value x. If we hold fewer than k values, x simply joins. Otherwise x belongs among the top k only if it is larger than the smallest of the current k. If it is, the smallest leaves and x joins; if not, x is skipped. So the one question we ask over and over is: what is the smallest of my k values, and how quickly can I replace it?
Now the question every beginner asks. The problem says largest, so why do we use a min-heap, which keeps the smallest at the top? Because the value we must look at and throw out is the weakest finalist, the smallest of the k largest. A min-heap puts exactly that value at the root, where peek reads it in one step. A max-heap would put the strongest finalist on top, which is the one value we never want to remove.
Could we keep the k values in a sorted list? We could, but inserting into a sorted list of k shifts up to k values, O(k) per value. A heap does better, as a look inside shows.
The tree is a picture of the array [4, 9, 7]. The children of the value at index i sit at indexes 2i + 1 and 2i + 2.
- array
- [4, 9, 7]
- root
- index 0, value 4
- children of 0
- indexes 1 and 2
1This min-heap holds 4, 9 and 7. Each parent is no larger than its children, so the smallest value, 4, is always at the root, index 0.
A heap is a tree drawn on top of an ordinary array. The value at index 0 is the root, and the two values below the value at index i live at indexes 2i + 1 and 2i + 2. The only rule is that a parent is never larger than its children. Because the tree is always as full as possible, a heap of k values is only about log2 of k levels deep.
That depth is why a heap is fast. To add a value with offer, the heap puts it at the end of the array and swaps it upward while it is smaller than its parent, at most one swap per level. To remove the root with poll, it moves the last value to the root and swaps it downward while it is larger than a child. Both take O(log k) steps. Reading the root with peek takes one step. Java's PriorityQueue is a min-heap that does all of this for us.
Why is the method correct? After each value, the heap holds exactly the k largest values seen so far, or all of them while fewer than k have been seen. Adding a value that beats the root and removing the root keeps that true, and skipping a value that does not beat the root keeps it true as well, since that value has k values at least as large. At the end, the heap holds the k largest values of the whole array, and its root, the smallest of them, is the k-th largest.
The mistake most people make here is to build PriorityQueue with Collections.reverseOrder(), a max-heap, because the word largest suggests it. With a max-heap of size k, the poll removes the biggest value instead of the weakest, and the method returns the wrong answer.
5Watching the heap keep the three largest
The picture plays the method on [7, 2, 9, 4, 9, 1] with k = 3. Each frame draws the heap as a tree, exactly as Java's PriorityQueue holds it after that step, and the panel shows the current value, the action, the heap's array and the root that peek returns.
Watch the root. It is always the weakest member of the current top three, and it is the only value any newcomer is compared with.
Each frame is the heap after one step, drawn from PriorityQueue's own array. The root is the smallest of the values kept.
- value x
- 7
- action
- add, heap not full
- heap array
- [7]
- peek
- 7
1The first value, 7, arrives. The heap has fewer than 3 values, so 7 goes in and is the root, the smallest member so far.
- value x
- 2
- action
- add, heap not full
- heap array
- [2, 7]
- peek
- 2
2Next comes 2. The heap is still not full, so 2 goes in. It is smaller than 7, so the heap moves it up to the root.
- value x
- 9
- action
- add, heap now full
- heap array
- [2, 7, 9]
- peek
- 2
3Then 9 goes in as the third value. The heap is now full with 2, 7 and 9, and its root, 2, is the weakest of the three.
- value x
- 4
- action
- 4 > 2, poll 2
- heap array
- [7, 9]
- peek
- 7
4The value 4 arrives and is compared with the root. Since 4 > 2, the root 2 is removed with poll, and 7 rises to the top.
- value x
- 4
- action
- offer 4
- heap array
- [4, 9, 7]
- peek
- 4
5Then 4 is offered. It is smaller than 7, so the heap moves it up to the root. The heap now holds 4, 9 and 7.
- value x
- 9
- action
- 9 > 4, poll 4
- heap array
- [7, 9]
- peek
- 7
6The second 9 arrives. Since 9 > 4, the root 4 is removed with poll, and 7 becomes the root again.
- value x
- 9
- action
- offer 9
- heap array
- [7, 9, 9]
- peek
- 7
7Then the second 9 is offered and settles below the root. The heap holds 7, 9 and 9, the three largest values so far.
- value x
- 1
- action
- 1 is not > 7, skip
- heap array
- [7, 9, 9]
- peek
- 7
8The last value, 1, is compared with the root 7. It is not larger, so it cannot be among the top three, and it is skipped.
- value x
- -
- action
- return peek()
- heap array
- [7, 9, 9]
- peek
- 7
9Every value has been seen. The heap holds the three largest, 7, 9 and 9, and its root, 7, is the third largest. We return 7.
Let us read the important frames back. In the first three frames the heap fills with 7, 2 and 9, and 2 rises to the root because it is the smallest. In the fourth and fifth frames 4 beats the root, so 2 is removed with poll and 4 is offered; notice that 4 then rises to the root, because it is now the smallest of 4, 9 and 7.
In the sixth and seventh frames the second 9 beats the root 4, so 4 leaves and 9 joins, and 7 is the root again. In the eighth frame 1 is compared with 7 and skipped without touching the heap at all. The heap ends as 7, 9, 9, the three largest values, and its root, 7, is the answer.
In all, three offers filled the heap, two values caused a poll and an offer each, and one was skipped after a single peek.
6The Java solution, read line by line
Here is the complete program. Java's PriorityQueue is a min-heap unless we tell it otherwise, so we need no comparator. main runs the example with k = 3, k = 1 and k = 6, a single element, and negative values with a duplicate. Each comment shows what that line prints.
Let us read kthLargest in the order it runs. The first line checks that k is between 1 and the length of the array, and throws an IllegalArgumentException if not, because otherwise the question has no answer. Then we create the heap; the k passed to it is only a starting size.
The for loop visits each value x once. While the heap holds fewer than k values, x is offered without any test, because every value is a finalist until the chairs are full. Once the heap is full, the else if compares x with heap.peek(), the weakest of the current top k. Only if x is larger do we poll the root and offer x.
Why compare before touching the heap? Because most values in a large array cannot enter the top k, and for them one peek is all the work. Offering first and polling afterwards would also be correct, but would spend O(log k) on every value.
When the loop ends, the heap holds the k largest values, and return heap.peek() gives back the smallest of them. For our example that is 7. With k = 1 the heap holds only the maximum, 9, and with k = 6 it holds every value and returns the minimum, 1.
7How much it costs, and the cases at the edges
Let us count on the example first. Six values were read and seven heap operations done, each on a heap only two levels deep, so at most one swap each. In general each of the n values costs at most one poll and one offer, about log2 of k swaps each, so the time is O(n log k). For a million values and k = 10 that is a few million simple steps.
The space is O(k), because the heap never holds more than k values, whatever the size of the array. When k is close to n the method costs about the same as sorting; the heap shines when k is much smaller than n.
| Approach | Time | Extra space | Works on a stream? |
|---|---|---|---|
| Sort a copy (brute force) | O(n log n) | O(n) | no |
| Find and remove the maximum k times | O(n k) | O(n) | no |
| Min-heap of size k | O(n log k) | O(k) | yes |
| Quickselect | O(n) average, O(n^2) worst | O(1), changes the array | no |
Now the edge cases, each run by main. A k outside 1 to n throws an exception at the very first line. With k = 1 the heap holds only the largest value, so we get the maximum, 9. With k equal to the length, the heap keeps every value and the root is the minimum, 1. A single element with k = 1 returns that element.
Repeated values are kept as separate entries, which is why both 9s sit in the heap. Negative numbers need no special care: for [-1, -1, -2] with k = 3 the heap keeps all three and returns -2. The strict comparison x > heap.peek() means a value equal to the root is skipped, which is safe, because swapping one copy of a value for another changes nothing.
8Follow-up questions
How does quickselect find the answer in O(n) on average?
Quickselect picks a value, called the pivot, and rearranges the array so larger values are on one side and smaller on the other, as quicksort does. If the pivot lands at position k counting from the largest, it is the answer; otherwise quickselect repeats on the one side that holds the answer. With a randomly chosen pivot each round throws away about half of what is left, so the total work is about n + n/2 + n/4 and so on, which is O(n) on average. In the worst case, with very unlucky pivots, it falls to O(n squared), and it reorders the array.
How would you keep the k-th largest of a stream of values that never ends?
The heap method already works one value at a time, so we keep the size k min-heap as a field of a class. Each add method offers the value if the heap has fewer than k values, or polls and offers if the value beats the root, and the k-th largest so far is always heap.peek(). Each add costs O(log k), and memory stays at O(k) however long the stream runs. Sorting and quickselect cannot do this, because they need all the values at once.
What changes for the k smallest values, or the k most frequent ones?
For the k smallest we flip the heap: a max-heap of size k, built with Collections.reverseOrder(), whose root is the largest of the k smallest, the weakest member for that question. For the k most frequent we first count each value with a HashMap, and then keep a min-heap of size k ordered by count, so the root is the least frequent of the current top k. The rule is the same in every version: the root of the heap is the member you would throw out first.
9Conclusion
We found the k-th largest element by keeping only the k largest values seen so far in a min-heap, comparing each new value with the heap's root, the weakest of the top k, and replacing the root only when the newcomer beats it. At the end the root is the answer, after O(n log k) time with O(k) space. The clue to remember is the phrase k-th largest, or any top k wording: only k values matter, so keep a heap of size k whose root is the one to throw out first.
Open with
Let me confirm the details: duplicates count separately, k is between 1 and n, and I should not modify the input. Sorting a copy and reading index n minus k works in O(n log n), but it orders every value when only the k largest matter.
Then, if they want more
While scanning, only the k largest values seen so far can still be the answer, so I keep them in a min-heap of size k. I use a min-heap, even though the question says largest, because the root must be the weakest member of the top k, the one a newcomer has to beat.
For each value, if the heap has fewer than k items I offer it. Otherwise, if the value is greater than peek, I poll the root and offer the value; if not, I skip it, which costs only one peek.
The invariant is that the heap always holds the k largest values seen so far, so at the end its root is the k-th largest, and I return peek. Each value costs at most O(log k), so it is O(n log k) time and O(k) space. It also works on a stream.
If average O(n) is required and changing the array is allowed, I would use quickselect with a random pivot.
About this answer
- Last updated
- 15 November 2026
- Written for
- Java 21, using only java.util
- Checked
- The Java solution was compiled and run, and each printed result matches the comment beside it. The pictures are checked against the format when the site is built. The explanation around the code is a study note: confirm anything critical against the documentation below. What the checks cover
- Where the question comes from
- Public interview write-ups, reworded by Scrivio; counted 55 times in that collection. How it is counted
- Official documentation
- PriorityQueue (Java 21), 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 "Find the k-th largest element in an unsorted array.": https://scrivio-interview-library.netlify.app/data-structures/solutions/find-the-k-th-largest-element-in-an-unsorted-array-184107/
Coding patterns, question 11 of 15 Back to the path
More heaps and top k questions