Skip to content
We areTOP 1%
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}

Problems

Heap / Priority Queue questions
#ProblemPlatformDifficultyOpen1st1st Visit2nd2nd VisitRevRevise
1Last Stone WeightLeetCodeEasy Solve Last Stone Weight on LeetCode (opens in a new tab)
2Kth Largest Element in a StreamLeetCodeEasy Solve Kth Largest Element in a Stream on LeetCode (opens in a new tab)
3Powering the Hero (hard version)CodeforcesEasy 1100Solve Powering the Hero (hard version) on Codeforces (opens in a new tab)
4Kth Largest Element in an ArrayLeetCodeMedium Solve Kth Largest Element in an Array on LeetCode (opens in a new tab)
5K Closest Points to OriginLeetCodeMedium Solve K Closest Points to Origin on LeetCode (opens in a new tab)
6Task SchedulerLeetCodeMedium Solve Task Scheduler on LeetCode (opens in a new tab)
7Phoenix and TowersCodeforcesMedium 1400Solve Phoenix and Towers on Codeforces (opens in a new tab)
8Productive MeetingCodeforcesMedium 1400Solve Productive Meeting on Codeforces (opens in a new tab)
9Digital LogarithmCodeforcesMedium 1400Solve Digital Logarithm on Codeforces (opens in a new tab)
10Potions (Easy Version)CodeforcesMedium 1500Solve Potions (Easy Version) on Codeforces (opens in a new tab)
11Lunar New Year and a WanderCodeforcesMedium 1500Solve Lunar New Year and a Wander on Codeforces (opens in a new tab)
12Merge k Sorted ListsLeetCodeHard Solve Merge k Sorted Lists on LeetCode (opens in a new tab)
13Find Median from Data StreamLeetCodeHard Solve Find Median from Data Stream on LeetCode (opens in a new tab)

Sign in to track your progress

Your checkboxes, streak and activity heatmap are saved to your account and sync across devices. It is free.
Sign in with email

New here? Create an account