Home/Learn/Heap & Priority Queue

Pattern Guide

Heap & Priority Queue

"O(log n) access to the min or max. Always."

Heaps power the top-K, merge K sorted, and median maintenance patterns. Learn when to use min-heap vs max-heap, the two-heap trick for medians, and heap-based graph algorithms.

Problems you can solve with this pattern

8 problems · click any to start solving

All heap
1Kth Largest Element in an ArrayMediumSolve
2Kth Largest Sum in a Binary TreeMediumSolve
3Find Median from Data StreamHardSolve
4Top K Frequent ElementsMediumSolve

A heap gives you O(log n) insert and O(1) peek at the minimum (min-heap) or maximum (max-heap). The key patterns: keep a heap of size k to maintain the top-k elements, use two heaps to maintain a running median, and use min-heap for Dijkstra's shortest path.

Min-heap vs Max-heap choice:
- "Find kth LARGEST" → use min-heap of size k (smallest of the k largest is at top)
- "Find kth SMALLEST" → use max-heap of size k (largest of the k smallest is at top)
- "Running median" → two heaps: max-heap for lower half, min-heap for upper half

Pattern Recognition

Problem SignalHeap Strategy
"kth largest / smallest"Min/max-heap of size k
"top k frequent"Build frequency map, heap on frequencies
"merge k sorted lists"Min-heap holding current head of each list
"running median"Two heaps: lower-half max-heap + upper-half min-heap
"shortest path (weighted)"Min-heap Dijkstra: [dist, node]
"task scheduler"Max-heap by frequency, simulate rounds

Two-heap trick — most elegant heap problem.

Two-Heap Pattern

Two heaps split data into two halves:
- Max-heap (lower half): top = largest of the smaller half
- Min-heap (upper half): top = smallest of the larger half

Median = average of both tops (even count) or top of larger heap (odd count).

Balance rule: sizes differ by at most 1. After every insert, rebalance if needed.
Heap pattern selector:
- "k-th largest/smallest overall" → min-heap of size k
- "k-th largest in stream" → maintain min-heap of size k, top = answer
- "merge k sorted lists/arrays" → min-heap of size k (one per list)
- "find median from stream" → two heaps (max-heap lower half + min-heap upper half)
- "Dijkstra / Prim's / scheduling" → min-heap with (cost, node)
- "maximize under budget constraint" → min-heap by cost + max-heap by benefit (IPO pattern)
- "sliding window median" → two heaps with lazy deletion