Heap / Priority Queue for Efficient Top K
Click "Start" to begin the algorithm
Medium
Find the kth largest element in an unsorted array.
Solve on LeetCode →Easy
Design class to find Kth largest in stream.
Solve on LeetCode →Sorting approach: O(n log n) - sorts all n elements
Heap approach: O(n log k) - maintains only k elements!
When k << n, this is MUCH faster. Example: Find top 10 from 1 million items.
// Kth Largest Element
function findKthLargest(nums, k) {
// Use min-heap of size k
const minHeap = new MinHeap();
for (let num of nums) {
minHeap.push(num);
// Keep heap size = k
if (minHeap.size() > k) {
minHeap.pop(); // Remove smallest
}
}
// Root of min-heap = kth largest
return minHeap.peek();
}
function topKFrequent(nums, k) {
// Step 1: Count frequencies
const freq = {};
for (let num of nums) {
freq[num] = (freq[num] || 0) + 1;
}
// Step 2: Use min-heap of size k
const minHeap = new MinHeap((a, b) => a[1] - b[1]);
for (let [num, count] of Object.entries(freq)) {
minHeap.push([num, count]);
if (minHeap.size() > k) {
minHeap.pop();
}
}
// Step 3: Extract elements
return minHeap.toArray().map(x => x[0]);
}