Stacks, Queues & Heaps
Heap / Priority Queue
🕶️
Picture this
A velvet-suited bouncer guards the VIP lounge, admitting only the top-K guests and ejecting the rest at the door.
When you see it
Signal words
If the prompt uses any of these, this pattern should come to mind first.
top kk largestk smallestmedianstreamclosestmerge k
Ask yourself
- “Top / Kth largest or smallest”?
- Running median or merging K sorted streams?
- Need the extreme element repeatedly, cheaply?
Canonical template
const heap = new MinHeap<number>();
for (const x of a) {
heap.push(x);
if (heap.size() > k) heap.pop();
}
return heap.peek();
Common pitfalls
Min-heap vs max-heap; choose the heap direction for the rank you keep.
Heap of size k for kth-largest, not full sort.