Skip to content
ajdevhub
1 min read

πŸ”οΈ Heaps (Priority Queues)

Min-heap: parent ≀ children. O(log n) push/pop. O(1) peek. C++ priority_queue defaults to max-heap β€” use greater<int> for min-heap.


Core Patterns

PatternApproachExample
Top K largestMin-heap of size KKeep K largest, peek = Kth
Top K smallestMax-heap of size KKeep K smallest
K-way mergePush (val, list, idx)Merge K sorted lists
Running medianMax-heap (lower) + min-heap (upper)Median of data stream

Templates

// Min-heap
priority_queue<int, vector<int>, greater<int>> minH;

// Top-K largest elements (min-heap of size K)
priority_queue<int, vector<int>, greater<int>> pq;
for (int x : nums) {
    pq.push(x);
    if ((int)pq.size() > k) pq.pop();
}
// pq.top() = Kth largest

// Custom comparator (min-heap by first element of pair)
auto cmp = [](pair<int,int>& a, pair<int,int>& b){ return a.first > b.first; };
priority_queue<pair<int,int>, vector<pair<int,int>>, decltype(cmp)> pq(cmp);

Complexity

OperationTime
Push / PopO(log n)
Peek (top)O(1)
Build heap from arrayO(n)