Heap / Priority Queue
Reach for it when the problem says
- Top k
- k-th largest
- merge sorted streams
- scheduling
- Solved
- 0/30Solved
- Problems
- 30Problems
- Variants
- 7Variants
Problems
7 variantsGreedy with a heap
0 of 7 solved- Last Stone WeightUp nextDeep diveEasyDecode Last Stone Weight
- Remove Stones to Minimize the TotalMediumDecode Remove Stones to Minimize the Total
- Maximum Average Pass RatioMediumDecode Maximum Average Pass Ratio
- Reorganize StringDeep diveMediumDecode Reorganize String
- Longest Happy StringMediumDecode Longest Happy String
- Furthest Building You Can ReachMediumDecode Furthest Building You Can Reach
- Minimum Number of Refueling StopsDeep diveHardDecode Minimum Number of Refueling Stops
Top K
0 of 6 solved- The K Weakest Rows in a MatrixDeep diveEasyDecode The K Weakest Rows in a Matrix
- Relative RanksDeep diveEasyDecode Relative Ranks
- Kth Largest ElementEssentialsSprintDeep diveMediumDecode Kth Largest Element
- K Closest Points to the OriginDeep diveMediumDecode K Closest Points to the Origin
- Top K Frequent WordsDeep diveMediumDecode Top K Frequent Words
- Sort Characters By FrequencyMediumDecode Sort Characters By Frequency
Scheduling simulation
0 of 5 solvedTwo heaps
0 of 3 solved- Total Cost to Hire K WorkersEssentialsDeep diveMediumDecode Total Cost to Hire K Workers
- Running MedianSprintDeep diveHardDecode Running Median
- Sliding Window MedianDeep diveHardDecode Sliding Window Median
Heap-backed design
0 of 3 solvedSort then heap
0 of 3 solved- Maximum Subsequence ScoreEssentialsDeep diveMediumDecode Maximum Subsequence Score
- Minimum Cost to Hire K WorkersDeep diveHardDecode Minimum Cost to Hire K Workers
- IPOSprintDeep diveHardDecode IPO
K-way merge
0 of 3 solved- Find K Pairs with Smallest SumsSprintDeep diveMediumDecode Find K Pairs with Smallest Sums
- Ugly Number IIMediumDecode Ugly Number II
- Design TwitterDeep diveMediumDecode Design Twitter
Pattern guide
A surprising number of interview problems keep asking the same question over and over: which item is the smallest (or largest) right now? The set keeps changing, so sorting once does not help. A heap answers that question in O(log n) per change, and once you can see it, a whole family of "hard" problems turns into a loop around push and pop.
What it is
A heap is a complete binary tree stored in an array, where every parent is at most its children (a min-heap) or at least them (a max-heap). The root is always the extreme value. push adds at the end and sifts up; pop moves the last item to the root and sifts down. Both are O(log n), and peek is O(1).
A priority queue is the interface ("give me the most urgent item next"); the heap is how it is built. Python ships heapq (a min-heap over a list; negate values for a max-heap). TypeScript has nothing built in, so every TypeScript solution on this site carries a small MinHeap class that takes a comparator. Flip the comparator and it becomes a max-heap.
A min-heap. The root, 2, is the smallest value. Nothing else about the order matters.
How to recognise it
Wording clues
| Phrase in the prompt | What it suggests |
|---|---|
"k largest", "k closest", "top k", "kth smallest" | A size-k heap with the worst candidate on top |
| "each time, take the largest / smallest" | Greedy loop: pop, change, push back |
| "median", "middle value" of a changing set | Two heaps: a max-heap below, a min-heap above |
"merge k sorted lists", "pairs with smallest sums", "nth number in a sequence" | K-way merge: heap of list heads |
| "arrives at time", "server", "room", "CPU", "free again at" | Event simulation with free and busy heaps |
| "smallest available id", "lowest free seat" | A counter plus a min-heap of returned ids |
Constraint clues
| Constraint | What it suggests |
|---|---|
n up to 10^5 and repeated min or max queries | O(n log n): one heap operation per step |
k much smaller than n | O(n log k) with a heap capped at k |
Times or values up to 10^9 | Jump the clock between events; never tick one unit at a time |
| At most 26 or 62 distinct keys | The heap is tiny, so each operation is effectively constant |
Input and output shape clues
- The input is a stream or a sequence of method calls (a class to design), and the answer must be ready after each call.
- The output is k items, or an order of items picked by priority (task order, server assignments).
- The input has two attributes per item (quality and wage, capital and profit), and the answer depends on a min or max of one and a sum of the other. That is "sort by one, heap the other".
Looks like it but isn't
- Sorting once is enough. If the set never changes after the start, just sort. A heap earns its place when items arrive or change between queries.
- Monotonic deque. "Max of every window" is a sliding-window deque problem in O(n). Reach for heaps when you need a median, or the window is not a simple slide.
- Meeting Rooms II (how many rooms?) is an intervals sweep. Meeting Rooms III (which room gets each meeting?) needs heaps, because you must know which room is free.
- Dynamic programming. Last Stone Weight II, or choosing items under a budget with no greedy rule, is DP. If the rule says "always the two heaviest", it is a heap.
Match each prompt clue to the heap shape it points to.
The sub-patterns
Top K
When it applies: you want the k best items by some key, or each item's rank. Keep a heap of size k with the worst candidate on top so eviction is cheap. For "k largest" that is a min-heap; for "k closest" it is a max-heap on distance.
Push 3, 2, 1. The heap has 3 items and its top, 1, is the 3rd largest so far.
Press Run (⌘ Enter) to see what happens.Press Run (⌘ Enter) to see what happens.Complexity: O(n log k) time, O(k) space. Known problems: Kth Largest Element, K Closest Points to the Origin, Top K Frequent Words, The K Weakest Rows in a Matrix.
Greedy with a heap
When it applies: the rule says "each step, take the biggest (or smallest) and do something to it", and the changed item goes back into play. Pop, act, push back. The greedy part is proving that the extreme item is always the right one; the heap makes each step O(log n). A twist called greedy with regret also lives here: commit tentatively (a ladder on every climb, a stop at every station), and when you run short, undo the cheapest commitment, which the heap hands you.
Max-heap of stones. Pop the two heaviest: 8 and 7.
Press Run (⌘ Enter) to see what happens.Press Run (⌘ Enter) to see what happens.Complexity: O(n log n) for n steps. Known problems: Last Stone Weight, Reorganize String, Furthest Building You Can Reach, Minimum Number of Refueling Stops.
Two heaps
When it applies: you need the boundary between the smaller half and the larger half of a changing set, usually a median. Keep a max-heap of the lower half and a min-heap of the upper half, balanced so the lower half has the same size or one more. The two tops are the middle. The same "two pools, compare tops" idea handles Total Cost to Hire K Workers, where the pools are the two ends of a line.
Add 5. It goes through low; low has one more item, so the median is low's top.
Press Run (⌘ Enter) to see what happens.Press Run (⌘ Enter) to see what happens.Complexity: O(log n) per add, O(1) per median. Known problems: Find Median from Data Stream (Running Median), Sliding Window Median, Total Cost to Hire K Workers. When items must also leave (a sliding window), add lazy deletion: count values to delete in a map and pop them only when they reach a top.
Sort then heap
When it applies: each item has two attributes and the score mixes a min or max of one with a sum of the other. Sort by the first attribute so it becomes "the current item's value", then keep the best k of the second attribute in a heap with a running sum. IPO is the same move with a pointer: sort by required capital, and push profits into a max-heap as they become affordable.
Pairs (nums2, nums1) sorted by nums2, largest first. Walking left to right, the current nums2 is always the minimum so far.
Press Run (⌘ Enter) to see what happens.Press Run (⌘ Enter) to see what happens.Complexity: O(n log n), dominated by the sort. Known problems: Maximum Subsequence Score, Minimum Cost to Hire K Workers, IPO.
K-way merge
When it applies: the answer comes from several already sorted sequences, and you need the overall smallest items in order. Put the head of each sequence in a min-heap. Pop the smallest, then push the next item from the same sequence. Sometimes the sequences are hidden: in Find K Pairs with Smallest Sums, each nums1[i] paired with all of nums2 is a sorted row; in Ugly Number II, the streams are "ugly numbers times 2, 3 and 5".
Each cell is nums1[i] + nums2[j]. Every row is sorted, so seed the heap with the first cell of each row: 3, 9, 13.
Press Run (⌘ Enter) to see what happens.Press Run (⌘ Enter) to see what happens.Complexity: O(N log k) for N items across k sequences; stop early when you only need the first few. Known problems: Merge K Sorted Lists, Find K Pairs with Smallest Sums, Ugly Number II, Design Twitter (the news feed merges each followed user's tweets).
Scheduling simulation
When it applies: things arrive over time and compete for resources: tasks for a CPU, tasks for servers, meetings for rooms, passengers for seats. Usually you need two orderings: which resource is best among the free ones, and which busy resource frees up next. Each ordering is a heap. Drive the clock by events and jump it forward when nothing is ready.
Servers weigh [3, 3, 2]. Task 0 (length 1) arrives at second 0 and takes the lightest free server, s2.
Press Run (⌘ Enter) to see what happens.Press Run (⌘ Enter) to see what happens.Complexity: O((n + m) log n) for n resources and m events. Known problems: Task Scheduler, Single-Threaded CPU, Process Tasks Using Servers, Meeting Rooms III, Car Pooling.
Heap-backed design
When it applies: you are asked to build a class whose methods keep returning "the smallest available" or "the kth largest so far". The heap is the core field. A recurring trick: when the universe is "every number from 1 up", store only a counter for the untouched tail and a min-heap of the numbers that came back. Everything in the heap is below the counter, so the heap wins whenever it is non-empty.
Seats 1 to 3 are booked. Seats from next upward have never been touched, so they need no storage.
Press Run (⌘ Enter) to see what happens.Press Run (⌘ Enter) to see what happens.Complexity: O(log n) per call. Known problems: Kth Largest Element in a Stream, Smallest Number in Infinite Set, Seat Reservation Manager.
What does this print?
import heapq
next_num, back = 1, []
def pop():
global next_num
if back:
return heapq.heappop(back)
next_num += 1
return next_num - 1
print(pop(), pop(), pop(), end=" ")
heapq.heappush(back, 2)
print(pop(), pop())A decision checklist
When a problem smells like a heap, ask these questions in order. The first "yes" usually names the sub-pattern.
Put the questions in the order you should ask them when choosing a heap sub-pattern.
- Tap the steps below in the right order.
Traps
- Wrong heap direction. For "k largest" you keep a min-heap; for "k smallest" a max-heap. Say out loud which item you want to evict, and put that one on top.
- Python has only a min-heap. Negate numbers for a max-heap, and un-negate exactly once on the way out. For strings, negation does not work: use
heapq.nsmallestwith a key, or a wrapper. - Tuples compare element by element.
(priority, item)breaks ties onitem, which may not be comparable (two dicts, two nodes). Add a counter or index as a tie-breaker:(priority, index, item). - Tie rules. "Smallest index on a tie" means the index is part of the key. Check whether
<or<=is right when releasing resources: a half-open meeting[start, end)frees its room atend. - Removing from the middle. Heaps only remove the top. When something must leave early (a sliding window, an unfollow), use lazy deletion or keep a membership set and skip stale entries on pop.
- Ticking the clock. With times up to 10^9, advance to the next event, never one unit at a time.
- Empty heap. Check before you
peekorpop: "no stones left", "no affordable project", "no station in reach".
Edge cases to always test: one item, all items equal, k equal to n, an empty start, values at the extremes of the range, and ties on the key.
How to talk it through
- Min-heap
- A complete binary tree in an array where every parent is at most its children, so the minimum is at index 0. Push and pop are O(log n).
- Size-k heap
- A heap capped at k items with the worst candidate on top, used to keep the top k of a stream in O(n log k).
- Two heaps
- A max-heap for the lower half and a min-heap for the upper half; their tops give the median.
- K-way merge
- Merging k sorted sequences by keeping each one's current head in a min-heap and refilling from the sequence you popped.
- Lazy deletion
- Marking items as deleted in a map and only removing them when they reach the top of the heap.
- Greedy with regret
- Committing to a choice tentatively and later undoing the cheapest commitment, which a heap hands you.