Heaps · Pattern 1 of 4
Top k, kth largest and repeatedly taking the best
Keep a min heap of size k: the top is the kth largest, and anything smaller than it can never make the cut. When you instead keep taking the biggest item and putting something back, use a max heap.
Watch the lesson
Concepts first, then the problem and every approach, step by step.
Space to play or pause · ← → to jump a step · click or drag the bar to seek
When to use it
- Kth largest or smallest, or the k best, closest or most frequent items
- A stream where the kth largest is asked after every new value
- Take the two biggest (or smallest), combine them, and put the result back
- Choose a team or a set of moves where only the best k so far should count
The template
// kth largest: a min heap that keeps the k largest values seen so far
int findKthLargest(int[] nums, int k) {
PriorityQueue<Integer> heap = new PriorityQueue<>();
for (int x : nums) {
heap.offer(x);
if (heap.size() > k) heap.poll(); // drop the smallest of the k + 1
}
return heap.peek(); // the weakest of the k largest
}
// repeatedly take the best two and put back what is left: a max heap
int lastStoneWeight(int[] stones) {
PriorityQueue<Integer> heap = new PriorityQueue<>(Collections.reverseOrder());
for (int s : stones) heap.offer(s);
while (heap.size() > 1) {
int a = heap.poll(), b = heap.poll();
if (a != b) heap.offer(a - b);
}
return heap.isEmpty() ? 0 : heap.peek();
} import heapq
def find_kth_largest(nums, k): # min heap of the k largest so far
heap = []
for x in nums:
heapq.heappush(heap, x)
if len(heap) > k:
heapq.heappop(heap) # drop the smallest of the k + 1
return heap[0] # the weakest of the k largest
def last_stone_weight(stones): # max heap: store negatives
heap = [-s for s in stones]
heapq.heapify(heap)
while len(heap) > 1:
a, b = -heapq.heappop(heap), -heapq.heappop(heap)
if a != b:
heapq.heappush(heap, -(a - b))
return -heap[0] if heap else 0 // kth largest: a min heap that keeps the k largest values seen so far
int findKthLargest(vector<int>& nums, int k) {
priority_queue<int, vector<int>, greater<int>> heap;
for (int x : nums) {
heap.push(x);
if ((int)heap.size() > k) heap.pop(); // drop the smallest of the k + 1
}
return heap.top(); // the weakest of the k largest
}
// repeatedly take the best two and put back what is left: a max heap
int lastStoneWeight(vector<int>& stones) {
priority_queue<int> heap(stones.begin(), stones.end());
while (heap.size() > 1) {
int a = heap.top(); heap.pop();
int b = heap.top(); heap.pop();
if (a != b) heap.push(a - b);
}
return heap.empty() ? 0 : heap.top();
} // a binary heap; less(a, b) is true when a should come out first
class MinHeap {
constructor(less = (a, b) => a < b) { this.a = []; this.less = less; }
get size() { return this.a.length; }
peek() { return this.a[0]; }
push(x) {
const a = this.a; a.push(x);
for (let i = a.length - 1; i > 0;) { // sift up
const p = (i - 1) >> 1;
if (!this.less(a[i], a[p])) break;
[a[i], a[p]] = [a[p], a[i]]; i = p;
}
}
pop() {
const a = this.a, top = a[0], last = a.pop();
if (a.length) {
a[0] = last;
for (let i = 0; ;) { // sift down
const l = 2 * i + 1, r = l + 1; let m = i;
if (l < a.length && this.less(a[l], a[m])) m = l;
if (r < a.length && this.less(a[r], a[m])) m = r;
if (m === i) break;
[a[i], a[m]] = [a[m], a[i]]; i = m;
}
}
return top;
}
}
// kth largest: a min heap that keeps the k largest values seen so far
function findKthLargest(nums, k) {
const heap = new MinHeap();
for (const x of nums) {
heap.push(x);
if (heap.size > k) heap.pop(); // drop the smallest of the k + 1
}
return heap.peek(); // the weakest of the k largest
}
// repeatedly take the best two and put back what is left: a max heap
function lastStoneWeight(stones) {
const heap = new MinHeap((a, b) => a > b);
for (const s of stones) heap.push(s);
while (heap.size > 1) {
const a = heap.pop(), b = heap.pop();
if (a !== b) heap.push(a - b);
}
return heap.size ? heap.peek() : 0;
} The variations
-
1A size-k heap for the kth largest
Push every item and pop whenever the heap grows past k. What is left are the k best, and the top is the kth best. It works for a stream too: keep the heap between calls. "Best" can be the closest point or a student's top five scores.
Now you solve -
2Count first, then take by frequency
Count with a hash map, then put the counts in a heap. To remove the fewest distinct values, pop the rarest first; for the most frequent words or characters, pop the most common first.
Now you solve -
3Repeatedly take the best and put it back
A greedy simulation: pop the biggest (or the two smallest), change it, push the result back. Each round is O(log n), so k rounds cost O(k log n) instead of re-sorting every time.
Now you solve -
4Keep the best k choices so far
Walk the input in a useful order and keep a min heap of the choices that currently count. When the heap is over budget, the smallest choice is the one to give up: the slowest engineer, or the smallest climb that should use bricks instead of a ladder.
Now you solve
Mistakes to avoid
- Using a max heap for "k largest": the top is then the best item, not the one to evict.
- Comparing distances with a square root: compare squared distances, they keep the same order and stay integers.
- In "maximum performance", forgetting to subtract the popped speed from the running sum.
Mark it done once you can write the template from memory and you have solved the worked examples yourself.