DSA · Intermediate · Pattern 5 of 10
Heap / Priority Queue
13 problems.
Your progress0%
- 1st Visit
- 0/13
- 2nd Visit
- 0/13
- Revise
- 0/13
About this pattern
A binary heap, available in C++ as priority_queue, returns the largest (or smallest) element in O(1) and supports insertion and removal in O(log n). Use it when you repeatedly need the current best element while the set keeps changing: the k largest items, merging several sorted streams, scheduling by priority, or a greedy that may later undo its worst earlier choice.
A min-heap of size k keeps the k largest elements seen so far in O(n log k) time. Signals include repeated extraction of an extreme value, the words top k or k-th largest, and processing events in order of cost.
// Max-heap by default; min-heap with greater<>.
priority_queue<int> maxHeap;
priority_queue<int, vector<int>, greater<int>> minHeap;
// Keep the k largest values: the min-heap top is the k-th largest.
for (int x : a) {
minHeap.push(x);
if ((int)minHeap.size() > k) minHeap.pop();
}
int kthLargest = minHeap.top();
// Pairs compare by first, then by second.
priority_queue<pair<int, int>> pq; // {priority, id}