0

Top K with a Heap

Keep a heap of exactly K elements of the opposite polarity, so the worst survivor is always at the top and cheap to evict.

Heap / Priority QueueO(n log k)New20 problems
18
mastery

Trigger phrases

If a problem statement sounds like one of these, try this pattern first.

k largest or smallest
k closest points
k most frequent

The template

Get this into muscle memory, then adapt the condition per problem.

const heap = new MinHeap();
for (const x of items) {
  heap.push(x);
  if (heap.size > k) heap.pop();
}
return heap.toArray();
Watch Heap: Push and Pop

If you are stuck

The generic hint ladder for this pattern, in order.

  1. 1Full sorting is O(n log n). You only need K of them.
  2. 2For k largest, a min heap lets you drop the smallest cheaply.
  3. 3Bucket sort by frequency can beat the heap when counts are bounded.

Drill it

Every problem in the bank that uses this pattern.

0 / 20 solved
1
MIntervals
2
3
MHeap / Priority Queue
4
MHeap / Priority Queue
5
MHeap / Priority Queue
6
MHeap / Priority Queue
7
MDesign (LLD)
8
MHeap / Priority Queue
9
MHeap / Priority Queue
10
EHeap / Priority Queue
11
12
MHeap / Priority Queue
13
14
MHeap / Priority Queue
15
EHeap / Priority Queue
16
17
18
19
HHeap / Priority Queue
20
MHeap / Priority Queue

Other patterns in Heap / Priority Queue