Skip to content
TOPIC · 13 PROBLEMS · 4 PATTERNS

Heaps

You keep needing the smallest or the largest of a pile that keeps changing. Sorting it again each time is too slow, and you never needed the rest in order anyway.

How to spot a heap problem

“k largest”Any "top k", "k closest" or "k most frequent". You only care about the best few, so keep just those and let the rest go.
“k sorted lists”Several inputs that are each sorted already. The next answer is always the front of one of them, and a heap tells you which.
“median”A middle value while numbers keep arriving. Split them into a lower half and an upper half and keep the two the same size.
“most / next”A simulation that keeps picking the biggest, cheapest or earliest thing left, then puts something back.

Four patterns cover almost everything

Top k

O(n log k)

Keep a min-heap of size k. Push each item, and when the heap grows past k, pop the smallest. What is left is the k largest.

Reach for it when you want the best k of many and k is much smaller than n.Go deeper: How a heap always knows the smallest

K-way merge

O(n log k)

Put the front of each sorted list in a heap. Pop the smallest, then push the next item from the same list.

Reach for it when the input is several sorted sequences, or a grid sorted along its rows and columns.Go deeper: How a heap always knows the smallest

Two heaps

O(log n) per add

A max-heap holds the lower half and a min-heap the upper half. Rebalance after each add so the middle sits on the tops.

Reach for it when you need the median of a stream or of a moving window.Go deeper: How a heap always knows the smallest

Greedy with a heap

O(n log n)

At each step take the most useful item left, act on it, and push back whatever changed.

Reach for it when a schedule or simulation always picks the largest, cheapest or most frequent option next.

The one template to memorise

Keep the k largest with a min-heap capped at size k. Once it clicks, most heap problems are this loop with a different thing being pushed.

solution.py
import heapq
def top_k(nums, k):
heap = [] # a min-heap of the k largest so far
for x in nums:
heapq.heappush(heap, x)
if len(heap) > k:
heapq.heappop(heap) # drop the smallest
return heap

Problems, easy to hard

Do them in order the first time
Next upIntervalsTrees