Skip to content

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 variants

Greedy with a heap

0 of 7 solved

Top K

0 of 6 solved

Scheduling simulation

0 of 5 solved

Two heaps

0 of 3 solved

Heap-backed design

0 of 3 solved

Sort then heap

0 of 3 solved

K-way merge

0 of 3 solved

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.

Pop the minimum, then push a new value
947283

A min-heap. The root, 2, is the smallest value. Nothing else about the order matters.

1/5
Quick check
You need the 5 largest values from a stream of a million numbers. Which heap keeps memory smallest?
Need a nudge? A hint rules out a wrong answer.

How to recognise it

Wording clues

Phrase in the promptWhat 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 setTwo 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

ConstraintWhat it suggests
n up to 10^5 and repeated min or max queriesO(n log n): one heap operation per step
k much smaller than nO(n log k) with a heap capped at k
Times or values up to 10^9Jump the clock between events; never tick one unit at a time
At most 26 or 62 distinct keysThe 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 the pairs0/5 matched

Match each prompt clue to the heap shape it points to.

Choose an item, then its match on the other side.

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.

Kth largest with a size-3 min-heap
3
0
2
1
1
2
5
3
6
4
4
5
heap = [1, 3, 2]

Push 3, 2, 1. The heap has 3 items and its top, 1, is the 3rd largest so far.

1/4
Python
import heapq def k_largest(nums, k): heap = [] for x in nums: heapq.heappush(heap, x) if len(heap) > k: heapq.heappop(heap) # evict the weakest return sorted(heap, reverse=True) print(k_largest([3, 2, 1, 5, 6, 4], 3))
Output
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.

Last Stone Weight: smash the two heaviest
172814

Max-heap of stones. Pop the two heaviest: 8 and 7.

1/4
Python
import heapq def last_stone(stones): heap = [-s for s in stones] # negate for a max-heap heapq.heapify(heap) while len(heap) > 1: y, x = -heapq.heappop(heap), -heapq.heappop(heap) if y != x: heapq.heappush(heap, -(y - x)) return -heap[0] if heap else 0 print(last_stone([2, 7, 4, 1, 8, 1]))
Output
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.

Quick check
In Furthest Building You Can Reach, you put a ladder on every climb until you have used one more ladder than you own. Which climb should switch to bricks?
Need a nudge? A hint rules out a wrong answer.

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.

Running median with two heaps
5
0
15
1
1
2
3
3
low = [5]high = []median = 5

Add 5. It goes through low; low has one more item, so the median is low's top.

1/4
Python
import heapq low, high = [], [] # low is a max-heap via negatives def add(x): heapq.heappush(low, -x) heapq.heappush(high, -heapq.heappop(low)) # largest of low moves up if len(high) > len(low): heapq.heappush(low, -heapq.heappop(high)) def median(): if len(low) > len(high): return -low[0] return (-low[0] + high[0]) / 2 for x in [5, 15, 1, 3]: add(x) print(x, "->", median())
Output
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.

Maximum Subsequence Score, k = 2
(4,2)
0
(3,3)
1
(2,1)
2
(1,3)
3

Pairs (nums2, nums1) sorted by nums2, largest first. Walking left to right, the current nums2 is always the minimum so far.

1/4
Python
import heapq def max_score(nums1, nums2, k): best = total = 0 heap = [] for floor, value in sorted(zip(nums2, nums1), reverse=True): heapq.heappush(heap, value) total += value if len(heap) > k: total -= heapq.heappop(heap) if len(heap) == k: best = max(best, total * floor) return best print(max_score([1, 3, 3, 2], [2, 1, 3, 4], 3))
Output
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".

K pairs with smallest sums: rows are sorted
246
1357
791113
11131517

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.

1/4
Python
import heapq def merge_sorted(lists): heap = [(lst[0], i, 0) for i, lst in enumerate(lists) if lst] heapq.heapify(heap) out = [] while heap: value, i, j = heapq.heappop(heap) out.append(value) if j + 1 < len(lists[i]): heapq.heappush(heap, (lists[i][j + 1], i, j + 1)) return out print(merge_sorted([[1, 4, 9], [2, 3, 10], [5]]))
Output
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.

Process Tasks Using Servers: free and busy heaps
1
0
↑task
2
1
3
2
2
3
1
4
2
5
free = (3,s0) (3,s1)busy = (1,s2)

Servers weigh [3, 3, 2]. Task 0 (length 1) arrives at second 0 and takes the lightest free server, s2.

1/4
Python
import heapq def assign(servers, tasks): free = [(w, j) for j, w in enumerate(servers)] heapq.heapify(free) busy, out, time = [], [], 0 for i, length in enumerate(tasks): time = max(time, i) if not free: time = max(time, busy[0][0]) # jump the clock while busy and busy[0][0] <= time: _, w, j = heapq.heappop(busy) heapq.heappush(free, (w, j)) w, j = heapq.heappop(free) out.append(j) heapq.heappush(busy, (time + length, w, j)) return out print(assign([3, 3, 2], [1, 2, 3, 2, 1, 2]))
Output
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.

Seat Reservation Manager: counter plus heap
1
0
2
1
3
2
4
3
↑next
5
4
freed = []

Seats 1 to 3 are booked. Seats from next upward have never been touched, so they need no storage.

1/4
Python
import heapq class SeatManager: def __init__(self, n): self.next = 1 self.freed = [] def reserve(self): if self.freed: return heapq.heappop(self.freed) self.next += 1 return self.next - 1 def unreserve(self, seat): heapq.heappush(self.freed, seat) m = SeatManager(5)print(m.reserve(), m.reserve(), m.reserve())m.unreserve(2)print(m.reserve(), m.reserve())
Output
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.

Predict the outputPython

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())
Need a nudge? Hints walk you through it.

A decision checklist

When a problem smells like a heap, ask these questions in order. The first "yes" usually names the sub-pattern.

Put it in order6 steps

Put the questions in the order you should ask them when choosing a heap sub-pattern.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.
Quick check
Workers have a quality and a minimum wage, everyone is paid the same rate per unit of quality, and you must hire exactly k as cheaply as possible. Which sub-pattern fits?
Need a nudge? A hint rules out a wrong answer.

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.nsmallest with a key, or a wrapper.
  • Tuples compare element by element. (priority, item) breaks ties on item, 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 at end.
  • 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 peek or pop: "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

Key terms
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.