Intuition
Keep a min-heap holding the k largest elements seen so far. Push each number; whenever the heap grows past k, pop the smallest. The heap's root then holds the kth largest.
Explanation
Idea
We don't need the whole array sorted — only the kth largest. Maintain a min-heap capped at size k containing the k biggest elements seen so far. Because it's a min-heap, its smallest element (the root) is the weakest of those k — precisely the kth largest overall once every element has been considered.
Algorithm
- For each
numinnums:- Push
numonto the heap. - If the heap size exceeds
k, pop the smallest element.
- Push
- After processing all numbers, the heap holds the k largest; return its root
heap[0].
Each push/pop is O(log k), and the heap never exceeds k elements.
Worked example: nums = [3,2,1,5,6,4], k = 2
Heap (size ≤ 2) after each push, popping when it exceeds 2:
| num | heap after push | after cap |
|---|---|---|
| 3 | [3] | [3] |
| 2 | [2,3] | [2,3] |
| 1 | [1,3,2] | pop 1 → [2,3] |
| 5 | [2,3,5] | pop 2 → [3,5] |
| 6 | [3,5,6] | pop 3 → [5,6] |
| 4 | [4,5,6] | pop 4 → [5,6] |
Root = 5, the 2nd largest.
Complexity
- Time: O(n log k).
- Space: O(k) for the heap.
Implementation
import java.util.PriorityQueue;
class Solution {
public int findKthLargest(int[] nums, int k) {
PriorityQueue<Integer> heap = new PriorityQueue<>();
for (int num : nums) {
heap.offer(num);
if (heap.size() > k) {
heap.poll();
}
}
return heap.peek();
}
}