Heap / Priority Queue · Medium
LeetCode 215: Kth Largest Element in an Array — solution
Solve LeetCode 215 with a size-k min-heap whose top is the k-th largest value — O(n log k) time, O(k) space (Quickselect gives O(n) on average).
Problem in plain words
Given an integer array and a number k, return the value that would be at position k if the array were sorted from largest to smallest. Duplicates count as separate elements, so in [5, 5, 1] the 2nd largest is 5. The challenge is to do better than fully sorting.
Example: nums = [7, 2, 9, 4, 9], k = 3. In descending order the array is 9, 9, 7, 4, 2, so the answer is 7.
Intuition
We only care about the k largest numbers. Keep them in a min-heap of size k: the smallest of the "top k" sits at the root. When a new number arrives, push it; if the heap grows past k, pop the minimum, because that number can no longer be among the top k. After all numbers are processed, the root is the k-th largest. Heap insertions use the bubble-up step, so each costs O(log k).
Approach
- Create an empty min-heap.
- For each number, push it onto the heap.
- If the heap size exceeds
k, pop the smallest element. - Return the heap's top.
Dry run
nums = [7, 2, 9, 4, 9], k = 3
| Number | Heap after push | Popped | Heap (size ≤ 3) |
|---|---|---|---|
| 7 | {7} | — | {7} |
| 2 | {2, 7} | — | {2, 7} |
| 9 | {2, 7, 9} | — | {2, 7, 9} |
| 4 | {2, 4, 7, 9} | 2 | {4, 7, 9} |
| 9 | {4, 7, 9, 9} | 4 | {7, 9, 9} |
The top of the heap is 7.
Java solution
class Solution {
public int findKthLargest(int[] nums, int k) {
PriorityQueue<Integer> heap = new PriorityQueue<>(); // min-heap
for (int x : nums) {
heap.offer(x);
if (heap.size() > k) {
heap.poll();
}
}
return heap.peek();
}
}Python solution
class Solution:
def findKthLargest(self, nums: List[int], k: int) -> int:
heap = []
for x in nums:
heapq.heappush(heap, x)
if len(heap) > k:
heapq.heappop(heap)
return heap[0]Complexity
| Measure | Cost | Why |
|---|---|---|
| Time | O(n log k) | Each of the n numbers does at most one push and one pop on a heap of size k. |
| Space | O(k) | The heap never holds more than k + 1 elements. |
Edge cases and common mistakes
- Using a max-heap of everything — pushing all n numbers and popping k − 1 times works but uses O(n) space.
- Removing duplicates — the k-th largest counts duplicates, so do not deduplicate with a set.
- k equal to the array length — the answer is the minimum element; the heap code handles it naturally.
- Negative numbers — no special handling needed; the heap orders them correctly.
›Can it be done in O(n)?
Yes, on average, with Quickselect: partition around a random pivot and recurse only into the side containing index n - k. Its worst case is O(n²), which a random pivot makes very unlikely. Since values are bounded here, counting sort also gives O(n + range).
›Why a min-heap rather than a max-heap?
A min-heap of size k throws away the smallest candidate, which is exactly the one that cannot be in the top k. Its root is then the k-th largest.
