Skip to main content

Heaps

Keep the smallest (or largest) thing within reach and stop caring about the order of everything else. A heap hands you its top in O(1) and absorbs a push or a pop in O(log n), which is exactly the trade a problem wants when it keeps asking "what is the best one right now?" while the set underneath it keeps changing.

987652min stays on toppeek in O(1)no order down here4push 4O(log n) to fix
The min sits on top and stays reachable in O(1); everything under it can be in any order. Pushing a new value only costs O(log n) to walk it back into place.

The structure​

A heap answers exactly one question fast: "what is the smallest (or largest) thing I am holding right now?" It does not answer "is x in here" and it does not answer "give me everything in order" without doing real work first. That narrowness is the whole design - a heap gives up almost every property a sorted structure has, in exchange for O(log n) insert and O(log n) extract-the-extreme, forever.

It is also the quiet workhorse behind "top k", "merge k sorted lists", Dijkstra, and any problem whose next step depends on "the best option so far."

What a heap answers​

Separate the question from the tool. A priority queue is an abstract interface with three operations: push a value, pop-best (remove and return the smallest or largest), and peek (look at the best without removing it). Nothing in that interface says how it is stored. A heap is one implementation of it, and the one almost everyone reaches for.

Two other implementations are easy to name, and both lose:

  • A sorted list peeks in O(1) and finds a slot in O(log n), but inserting shifts everything after it, so a push is O(n).
  • A balanced BST does push and pop-best in O(log n), the same asymptotics as a heap, but it pays for pointers, rotations and a full ordering you never read. A heap gets the same bounds from a plain array and a rule about one parent and two children.

The heap wins because the interface only ever asks about the best element, so there is no reason to keep the rest in order.

The heap property​

A min-heap is a binary tree where every parent is <= both of its children. A max-heap flips the inequality: every parent is >= both children. That is the entire rule, and it says nothing else - nothing about left versus right, nothing about one sibling versus another, nothing about any node compared to a node it is not a direct ancestor or descendant of.

78349213 > 2 - allowedsmallest overall

That single restriction has two consequences worth stating plainly, because both are exactly what people expect a heap to not do:

GOTCHAA heap is not sorted, and you cannot search it

Check the rule against a few candidates. Each round shows a tree and its array; click the child of the edge that breaks the heap property, or say it is already a heap.

Is this a heap?
328512984428932709930281512293844425896327708999
Violating edge
Is this a min-heap? Click the child of the edge that breaks the rule, or answer "It is a heap". 0 / 0

A complete tree lives in an array​

A heap is always a complete binary tree: every level is full except possibly the last, and the last level fills strictly left to right, with no gaps. Completeness is the whole reason a heap can be packed into a plain array with no pointers at all - the level-order array of a complete tree never has a hole, so index arithmetic alone finds every parent and child.

783492110312273844596parent = (1-1)//2 = 0left = 2(1)+1 = 3right = 2(1)+2 = 4
You haveFormula (0-indexed)On the array above
index iitselfindex 1 holds 3
i's left child2*i + 1index 3 holds 7
i's right child2*i + 2index 4 holds 8
i's parent (i > 0)(i - 1) // 2index 0 holds 1
the last non-leaf index(n // 2) - 1used by heapify - see Building a heap in linear time
def parent(i): return (i - 1) // 2
def left(i): return 2 * i + 1
def right(i): return 2 * i + 2
DID YOU KNOWDid You Know?

This is the exact same array you saw on Representation for a level-order-serialized binary tree. A heap does not need a new storage idea - it is the special case where the level-order array happens to have no null holes, because the tree is always complete.

Sift up: push​

Pushing a value is two moves: append it as the new last leaf, then let it swim up past any parent it is smaller than (min-heap). Each step is one comparison and, at most, one swap - and the path it can possibly take is bounded by the tree's height, which is log n for n elements. That bound is where push gets its O(log n).

1031227384459607append 0 at index 7. parent = (7-1)//2 = 3, value 7. 0 < 7 → swap.1031220384459677now at index 3. parent = (3-1)//2 = 1, value 3. 0 < 3 → swap.1001223384459677now at index 1. parent = (1-1)//2 = 0, value 1. 0 < 1 → swap.0011223384459677index 0 is the root - no parent left to compare. sift-up stops.
Pushing 0 onto the heap. It starts as the new last leaf and swaps upward with its parent at every step, because 0 is smaller than everything above it - the worst case, all the way to the root.
Python
def push(heap, value):
heap.append(value)
i = len(heap) - 1
while i > 0:
p = (i - 1) // 2
if heap[p] <= heap[i]:
break # parent is already smaller - done
heap[p], heap[i] = heap[i], heap[p]
i = p
FIG. HEAP SIFT UP● INTERACTIVE
visualization loads as you reach it
MNEMONIC

Sift UP starts at the bottom and climbs; sift DOWN starts at the top and sinks. push only ever disturbs the single root-to-leaf path the new element sits on, which is why it never needs to look at any other branch of the tree.

Sift down: pop​

Popping the minimum has to solve a harder problem: the root is leaving, and something has to become the new root without breaking completeness. The answer is to swap the last leaf into the root's place, shrink the array by one, then let that element sink down past whichever child is smaller, until it finds a spot where it is <= both children or it runs out of children.

pop returns the old root, 0. the last leaf (value 7)takes index 0, and the array shrinks to 7 cells:70112233844596at index 0, value 7. children are 1 and 2 -the smaller is 1 (index 1). 7 > 1 → swap.10712233844596at index 1, value 7. children are 3 and 8 -the smaller is 3 (index 3). 7 > 3 → swap.10312273844596at index 3, children would be indices 7 and 8 -out of range. sift-down stops.
Popping the heap left by the push above. The last leaf takes the root's place, then sinks down by always swapping with its SMALLER child, until it lands back where the run started - the same heap we began with.
Python
def pop(heap):
heap[0], heap[-1] = heap[-1], heap[0]
root = heap.pop() # the actual minimum, already swapped out
n = len(heap)
i = 0
while True:
smallest, l, r = i, 2 * i + 1, 2 * i + 2
if l < n and heap[l] < heap[smallest]:
smallest = l
if r < n and heap[r] < heap[smallest]:
smallest = r
if smallest == i:
break # both children are already >= i
heap[i], heap[smallest] = heap[smallest], heap[i]
i = smallest
return root
visualization loads as you reach it
MENTAL MODELThe last element is the only one that can be removed without breaking completeness, which is why it is the one that moves in - not the root's child.
GOTCHASift down swaps with the smaller child, never blindly the left one

Now try it yourself. The bench below is free play next to the two real-code playgrounds above: push a value or pop the top, one comparison per step. Open the session for Pushpop, Replace and Heapify random, and hover a node or an array cell there to see its twin.

Heap lab
256789
moving valuecompared with
1
A min-heap. Push a value or pop the top, one comparison per step. Open session for Pushpop, Replace, Heapify random and the array twin. n = 6 · comparisons = 0
1 / 1

pushpop and replace​

Pushing and then popping costs two sifts: one up, one down. heapq has two fused operations that do the same job with one sift, and they differ only in the order of the two halves.

  • heappushpop(h, x) pushes x first, then pops. It returns the smallest of the heap plus x. If x is already <= the root, the heap is not touched at all and x comes straight back.
  • heapreplace(h, x) pops first, then pushes x. It always returns the old root, even when x is smaller, then sifts x down from the root.
import heapq
 
h = [2, 5, 3]
print(heapq.heappushpop(h, 1), h) # 1 beats the root: returned, heap untouched
print(heapq.heappushpop(h, 4), h) # the old root 2 leaves, 4 sinks in
 
h = [2, 5, 3]
print(heapq.heapreplace(h, 9), h) # old root 2 returned, 9 sifts down
h = [2, 5, 3]
print(heapq.heapreplace(h, 1), h) # old root 2 returned even though 1 is smaller
 
print(heapq.heappushpop([], 7)) # empty heap: x is the answer
try:
heapq.heapreplace([], 1)
except IndexError as e:
print("IndexError:", e)
1 [2, 5, 3]
2 [3, 5, 4]
2 [3, 5, 9]
2 [1, 5, 3]
7
IndexError: index out of range

Reach for heappushpop when the heap is a fixed-size filter and you only care about what falls out. The classic case is the bounded top-k heap: once it holds k values, heappushpop(top, x) keeps the k largest seen so far and discards the loser in one sift. Reach for heapreplace when you are swapping the current best for its successor, as in a k-way merge, where you pop a list's head and push that list's next value. The empty case is the difference to remember: heappushpop on an empty heap returns x, but heapreplace has nothing to pop and raises IndexError.

Building a heap in linear time​

Given n unsorted values, pushing them one at a time costs n pushes at O(log n) each - O(n log n) total. Heapify does better: O(n). The trick is to sift down starting from the last non-leaf node and work backward to the root, rather than sifting up from an empty heap.

def heapify(heap):
n = len(heap)
for i in range(n // 2 - 1, -1, -1): # last non-leaf down to the root
_sift_down(heap, i, n)

The O(n) bound looks surprising until you count how far each node can possibly sink. A node at height h (measuring up from the leaves) can sift down at most h levels, and there are roughly n / 2h+1 nodes at each height. Summing cost over every height:

total work <= sum over h of (n / 2^(h+1)) * h
= n * sum over h of h / 2^(h+1)
= n * 1 (that infinite sum converges to 1)
= O(n)

Half the nodes are leaves and do zero work; a quarter are one level up and do at most one swap; an eighth do at most two - the work per node shrinks geometrically exactly as fast as the node count does, and the product sums to a constant, not a log n.

DID YOU KNOWDid You Know?

heapq.heapify uses exactly this bottom-up pass, so building a heap from a list you already have is always the right move over n individual heappush calls. heapq.heapify(data) mutates data in place in O(n); looping heappush(heap, x) for x in data builds a valid heap (not the same one) in O(n log n).

Race the two builds on the same array. Heapify sifts down from the last non-leaf; the push build sifts each new value up. Compare the comparison counts when both finish.

n pushes vs heapify
one push at a time · O(n log n)
empty heap
bottom-up heapify · O(n)
151413121110987654321
moving valuecompared with
1
Unordered array of 15. Start at the last non-leaf, index 6. pushes: 0 comparisons · heapify: 0
1 / 99

Heapsort​

Build a max-heap, then repeat: swap the root with the last cell of the heap, shrink the heap by one, and sift the new root down. The array splits into a heap on the left and a sorted tail on the right, and the tail grows until the heap is gone.

def heapsort(a):
n = len(a)
def sift(i, n):
while True:
l, r, b = 2 * i + 1, 2 * i + 2, i
if l < n and a[l] > a[b]: b = l
if r < n and a[r] > a[b]: b = r
if b == i: return
a[i], a[b] = a[b], a[i]
i = b
for i in range(n // 2 - 1, -1, -1): # heapify, O(n)
sift(i, n)
for end in range(n - 1, 0, -1): # n - 1 extractions, O(log n) each
a[0], a[end] = a[end], a[0]
sift(0, end)
return a
 
print(heapsort([5, 2, 8, 1, 9, 3])) # [1, 2, 3, 5, 8, 9]
print(heapsort([])) # []
  • O(n log n) always. The build is O(n) and the n - 1 extractions cost O(log n) each. There is no bad input and no good one.
  • O(1) auxiliary space. It sorts in place; the only extra memory is a few indices.
  • Not stable. The swap with the last cell jumps equal values over each other, so their original order is not preserved.
  • Usually slower than the alternatives. Sift-down hops between indices i and 2i + 1, which are far apart in memory, so it is cache-unfriendly. Quicksort and Python's Timsort scan neighbouring cells and win in practice. Heapsort earns its place where the worst case must be O(n log n) with no extra memory.

Step through one run and watch the sorted tail grow from the right. The all-equal preset shows why stability is not a property you can read off plain integers.

Heapsort in place
41035189240101325314859627
moving nowcompared withsorted tail
1
Build max-heap: fix every non-leaf, last one first (index 3). heap size 8
1 / 49

What a heap is not​

A heap is a narrow tool, and most of its bugs come from expecting it to be a wider one.

Sorted arrayBSTSortedListHeap
Find the min/maxO(1)O(log n) averageO(1)O(1) - it is always the root
Remove the min/maxO(n) (shift)O(log n) averageO(log n)O(log n), always
Search an arbitrary valueO(log n)O(log n) averageO(log n)O(n) - no ordering rules out a subtree
InsertO(n) (shift)O(log n) average, O(n) worstO(log n)O(log n), always
In-order gives all elements sortedyes, triviallyyesyesno
Balance guaranteen/anone, unless self-balancingn/a - a list of bounded-size sorted chunksalways complete, by construction

SortedList is sortedcontainers.SortedList, a third-party package that is not in the standard library. It matches a heap on peek and pop-best and beats it on search and ordered iteration, so it is the right tool when you need those too. A heap is still the lighter pick when pop-best is the only question.

  • Not sorted. Reading a heap's array left to right is not reading the values in order - only heap[0] is guaranteed to be anything.
  • Not a BST. There is no left < node < right invariant, so nothing supports a binary search once you leave the root.
  • Not a general priority structure with fast arbitrary deletes. Removing "the element with value 8, wherever it is" is not a heap operation - you would have to find it first, which is the O(n) search this whole page keeps warning about. (A heap with an index map to support that is a real, more complex structure, not the one described here.)

heapq in Python​

The whole API​

Python's heapq module implements a min-heap: every classic function (heappush, heappop, heapify, ...) keeps the smallest value at index 0, and none of them takes a "compare the other way" option. The next section covers how to get a max-heap anyway.

import heapq
 
h = [5, 1, 8, 3]
heapq.heapify(h) # O(n), in place
heapq.heappush(h, 2) # O(log n)
smallest = heapq.heappop(h) # O(log n), returns 1
peek = h[0] # O(1) - the min is always index 0, no pop needed
FunctionCostDoes
heapify(list)O(n)Turns an existing list into a heap, in place.
heappush(h, x)O(log n)Appends then sifts up.
heappop(h)O(log n)Swaps last-to-root, shrinks, sifts down; returns the old root.
heappushpop(h, x)O(log n)Push x, then pop the smallest - one sift, not two.
heapreplace(h, x)O(log n)Pop the root, then push x - one sift, raises on an empty heap.
h[0]O(1)Peek the minimum without removing it.
heapq.merge(*its)O(log k) per itemLazily merges k already-sorted iterables into one sorted stream.
heapq.nlargest(k, it)O(n log k)The k largest, without you managing a heap by hand.
heapq.nsmallest(k, it)O(n log k)The k smallest, same idea.

heappushpop and heapreplace are the fused operations from pushpop and replace. The heap functions mutate a plain list, which is why h[0] and len(h) just work.

heapq.merge is a lazy k-way merge. Each input must already be sorted. The result is a generator that holds one head per input in a small heap, so it never builds the merged list and uses O(k) memory however long the inputs are. It also takes key= and reverse=True:

a, b, c = [1, 2], [0, 3, 4], [5]
print(list(heapq.merge(a, b, c))) # [0, 1, 2, 3, 4, 5]
print(list(heapq.merge([5, 3, 1], [4, 2], reverse=True))) # [5, 4, 3, 2, 1]

nlargest and nsmallest take key=, like sorted. The key picks what is compared; the original items come back:

words = ["pear", "fig", "banana", "kiwi", "apple"]
print(heapq.nlargest(2, words, key=len)) # ['banana', 'apple']
print(heapq.nsmallest(2, words, key=len)) # ['fig', 'pear']

Which tool to use depends on how big k is next to n:

  • k = 1: use max(it) or min(it). One pass, no heap, and both take key= too. The heapq docs say the same.
  • k small next to n: use nlargest / nsmallest. O(n log k) time and O(k) memory, and it works on a stream you cannot hold in memory.
  • k near n: use sorted(it)[:k]. The heap work approaches n log n anyway, and sorted runs in C with a smaller constant. The heapq docs recommend sorted for larger k.

The one pattern worth internalizing on sight: "the k largest" is a size-k min-heap, which reads backward the first time you meet it.

MNEMONIC

To keep the k largest, throw away the smallest - and a min-heap makes "the smallest" free to find. Push every value in; the moment the heap exceeds size k, pop it - which discards the current minimum of your candidate set. Whatever survives to the end is the k largest overall, and the heap's own root, at every point along the way, is the weakest member still standing - exactly the one you want to be able to evict in O(log k).

def k_largest(nums, k):
heap = []
for x in nums:
heapq.heappush(heap, x)
if len(heap) > k:
heapq.heappop(heap) # evict the current smallest of the k
return heap # k largest, in no particular order

Max-heaps​

WARNING

The classic heapq functions are always a min-heap. To use them as a max-heap, negate every value going in and negate it again coming out: heappush(h, -x), then -heappop(h). This is the standard trick, not a workaround - every "max-heap" you see in Python solutions is a min-heap of negated values.

Negation only works for numbers. -"abc" raises TypeError, and so does negating a tuple. For strings, or any value with no meaningful -, wrap the value in a class whose __lt__ is reversed, since heapq only ever asks a < b:

class Rev:
def __init__(self, s): self.s = s
def __lt__(self, other): return self.s > other.s # reversed on purpose
 
w = []
for s in ["pear", "apple", "zebra", "mango"]:
heapq.heappush(w, Rev(s))
print(heapq.heappop(w).s) # zebra - the largest string comes out first

Python 3.14 added public max-heap functions: heapify_max, heappush_max, heappop_max, heappushpop_max and heapreplace_max. They mirror the min-heap functions but keep the largest value at index 0, with no negation and no wrapper class. The Pyodide that runs on this site is 3.14.2, so these run here.

import heapq
 
h = [3, 1, 4, 1, 5]
heapq.heapify_max(h)
print(h) # [5, 3, 4, 1, 1]
heapq.heappush_max(h, 9)
print(h) # [9, 3, 5, 1, 1, 4]
print(heapq.heappop_max(h), h) # 9 [5, 3, 4, 1, 1]
print(heapq.heappushpop_max(h, 10), h) # 10 [5, 3, 4, 1, 1]
print(heapq.heappushpop_max(h, 2), h) # 5 [4, 3, 2, 1, 1]
print(heapq.heapreplace_max(h, 0), h) # 4 [3, 1, 2, 1, 0]
print(h[0]) # 3

heappush_max(h, 9) leaves [9, 3, 5, 1, 1, 4]: the 9 is appended at index 5, sifts up past its parent 4, then past 5, and stops at the root. 10 in heappushpop_max beats the root, so it comes straight back and the heap is untouched, exactly like heappushpop on a min-heap.

GOTCHAThe max-heap functions need Python 3.14

Tuples, ties and tiebreakers​

heapq compares whatever you push using <, which means pushing a tuple compares it element-by-element, left to right. That is useful - it is how you attach a priority to a payload - and it is also a trap:

GOTCHAUn-orderable payloads crash the tuple trick
h = []
heapq.heappush(h, (1, {"job": "a"}))
heapq.heappush(h, (1, {"job": "b"}))
# TypeError: '<' not supported between instances of 'dict' and 'dict'

The counter also makes ties first in, first out, because earlier pushes get smaller counters:

import itertools
counter = itertools.count()
h = []
for pri, name in [(2, "b"), (1, "a"), (2, "c"), (1, "d")]:
heapq.heappush(h, (pri, next(counter), name))
print([heapq.heappop(h)[2] for _ in range(4)]) # ['a', 'd', 'b', 'c']

Two ways to skip the tuple, both of which make the object itself orderable:

  • Define __lt__ on a class. heapq only needs <, so one method is enough. Compare only the priority and ties pop in no promised order:
    class Job:
    def __init__(self, pri, name): self.pri, self.name = pri, name
    def __lt__(self, other): return self.pri < other.pri
  • Use @dataclass(order=True) and exclude the payload. Fields compare in declaration order, and field(compare=False) removes the payload from the comparison, so it is never reached even when the other fields tie:
    from dataclasses import dataclass, field
     
    @dataclass(order=True)
    class Task:
    pri: int
    seq: int # the tiebreaker, still explicit
    payload: dict = field(compare=False)
     
    h = []
    for seq, (pri, name) in enumerate([(2, "b"), (1, "a"), (2, "c")]):
    heapq.heappush(h, Task(pri, seq, {"job": name}))
    print([heapq.heappop(h).payload["job"] for _ in range(3)]) # ['a', 'b', 'c']

For max-first priorities in a tuple, negate just the number: (-pri, seq, payload). The tuple as a whole cannot be negated.

Lazy deletion and decrease-key​

heapq has no delete and no decrease-key. Removing an arbitrary entry means finding it, which is O(n), then repairing the heap. The standard answer is lazy deletion: never remove it, mark it stale, and throw it away if it ever surfaces at the root. A stale entry stays buried, costing nothing, until a pop reaches it.

The heapq documentation's priority-queue recipe does exactly this. Entries are mutable lists [priority, count, task]; a dict maps each task to its live entry; removing a task overwrites its entry with a REMOVED marker:

import heapq, itertools
 
pq = [] # the heap of entries
entry_finder = {} # task -> its live entry
REMOVED = '<removed>' # marker for a stale entry
counter = itertools.count() # unique tiebreaker
 
def add_task(task, priority=0):
if task in entry_finder:
remove_task(task) # decrease-key = mark old stale, push new
entry = [priority, next(counter), task]
entry_finder[task] = entry
heapq.heappush(pq, entry)
 
def remove_task(task):
entry = entry_finder.pop(task)
entry[-1] = REMOVED
 
def pop_task():
while pq:
priority, _, task = heapq.heappop(pq)
if task is not REMOVED: # skip stale entries on the way out
del entry_finder[task]
return task
raise KeyError('pop from an empty priority queue')

Decrease-key is the same move. To change a task's priority, mark its entry stale and push a fresh one. Running it:

add_task("a", 5); add_task("b", 3); add_task("c", 4)
add_task("a", 1) # a: 5 -> 1, the old entry goes stale
remove_task("b")
print(len(pq)) # 4 (two stale entries still buried)
print(pop_task(), pop_task()) # a c
print(len(pq)) # 1 (the stale a-at-5 is still buried)

len(pq) is 4 right after the removals because the stale entries are still in the heap. The second pop_task pops the stale b, discards it, and returns c. Popping again would discard the last stale entry and then raise KeyError, the empty-queue case.

When there is no entry to flip, use a version check instead. Dijkstra's algorithm does this: push (dist, node) every time a shorter distance is found, keep the best known distance per node, and on pop, skip any entry whose distance is worse than the best:

best = {"a": 9}
h = [(9, "a")]
best["a"] = 4; heapq.heappush(h, (4, "a")) # shorter path found: push again
while h:
d, n = heapq.heappop(h)
if d > best[n]:
continue # stale: a better entry exists
print((d, n)) # (4, 'a'), once

The sliding-window maximum below uses the same idea with an index as the version: an entry is stale once its index leaves the window. Step through it and watch the discard steps; stale values stay buried until they reach the top.

Lazy deletion
908112233475empty heap
enteringwindow / topstale, buried
1
Window of 3 over [9, 8, 1, 2, 3, 7]. A max-heap of (value, index): entries that leave the window are never searched for. heap size 0 · stale buried 0
1 / 13

Stale entries make the heap bigger than the live set, so memory is O(pushes) rather than O(live). Each stale entry is popped exactly once in total, so the amortized cost per operation stays O(log n).

An indexed heap is worth it only when stale entries pile up. That means a hot loop with millions of priority updates per live item, or a hard memory cap. An indexed heap keeps a position map from item to array index, so decrease-key sifts the item in place in O(log n) and nothing goes stale. It is more code, heapq will not do it for you (you write your own sift functions, as in Sift down: pop), and for contest and interview code lazy deletion is almost always the better trade.

Patterns​

Every pattern below has its problems on Heap Problems.

Top K​

Only the best k ever matter. Keep a heap of at most k candidates and let everything else fall off the end, so the work scales with k instead of with the whole input.

The trick is the direction. To keep the k largest, hold a min-heap: its top is the weakest survivor, which is exactly the one a better newcomer has to beat.

import heapq
 
def top_k(stream, k):
h = []
for x in stream:
if len(h) < k:
heapq.heappush(h, x)
elif x > h[0]:
heapq.heapreplace(h, x)
return sorted(h, reverse=True)
 
print(top_k([5, 12, 3, 18, 7, 21, 9, 14], 3))
# [21, 18, 14]

Cost: O(n log k) time, O(k) space, and the heap never grows past k. Because it only ever looks at one element at a time it works on a stream you cannot store. Sorting is O(n log n) and needs everything in memory; a single heapq.nlargest(k, it) is this loop. When k is close to n, sorting wins.

Try it: push k down to 1 and watch the heap shrink to the running maximum.

Top K from a stream
5123187219142161125empty heap
arriving nowheap topevicted
1
Keep the 3 largest. A min-heap of size 3: its top is the weakest survivor. heap size 0 · O(n log k)
1 / 14

Practice problems.

K-way Merge​

You have k sorted sources and want one sorted output. Never merge them all at once: keep one cursor per source and a min-heap of the k current heads. Pop the smallest head, emit it, and push the next element from the same source.

import heapq
 
def merge_k(lists):
h = [(l[0], i, 0) for i, l in enumerate(lists) if l]
heapq.heapify(h)
out = []
while h:
v, i, j = heapq.heappop(h)
out.append(v)
if j + 1 < len(lists[i]):
heapq.heappush(h, (lists[i][j + 1], i, j + 1))
return out
 
print(merge_k([[1, 4, 7, 10], [2, 5, 8], [3, 6, 9, 12]]))
# [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12]

The list index i in the tuple is the tiebreaker, so equal values never fall through to comparing payloads (see Tuples, ties and tiebreakers). Cost: O(N log k) for N total elements, with a heap of size k. The stdlib already ships this loop as heapq.merge.

Try it: pick "One list runs out early" and watch the heap shrink as sources empty.

K-way merge
1471025836912
123
just pushed / appendedhead in the heapconsumed
1
Seed the min-heap with the head of each of the 3 lists. heap size 3 <= k = 3 · O(N log k)
1 / 12

Practice problems.

Two Heaps​

You need the middle of a stream, not an extreme. Split the values into a small half and a large half: a max-heap holds the smaller values, a min-heap the larger. Both tops are the two middle candidates, so the median is one peek away.

import heapq
 
class Median:
def __init__(self):
self.lo, self.hi = [], [] # lo: max-heap (negated), hi: min-heap
 
def add(self, x):
heapq.heappush(self.lo, -x)
heapq.heappush(self.hi, -heapq.heappop(self.lo))
if len(self.hi) > len(self.lo):
heapq.heappush(self.lo, -heapq.heappop(self.hi))
 
def median(self):
if len(self.lo) > len(self.hi):
return -self.lo[0]
return (-self.lo[0] + self.hi[0]) / 2
 
m = Median()
out = []
for x in [5, 15, 1, 3]:
m.add(x)
out.append(m.median())
print(out)
# [5, 10.0, 5, 4.0]

Each value takes the long way round (into lo, over to hi, maybe back) so the invariant "everything in lo is at most everything in hi, and the sizes differ by at most one" is restored by construction. Cost: O(log n) per add, O(1) per median, O(n) space.

Try it: step through and watch which heap each arriving value ends up in.

Running median with two heaps
5151387910202
empty heapempty heap
arriving nowheap topalready seen
1
Left: a max-heap of the smaller half. Right: a min-heap of the larger half. The median lives at their tops. left 0 · right 0
1 / 11

Practice problems.

Earliest to Finish​

Sort the events by start, then keep a min-heap of the moments things end. The heap's top is always the next resource to free up, so each new arrival either reuses it or opens a new one.

Practice problems.

Window Extremes​

A sliding window needs its max (or min) at every step. Push each element as it enters and lazily discard the top only once it has slid out of the window - stale entries buried deeper in the heap can wait.

The monotonic deque does the same job in O(n) instead of O(n log n), because it drops dominated elements the moment they arrive instead of keeping them in a heap. Reach for the heap when the window is not a plain sliding one or you also need the k-th best; otherwise see Fixed Window for the deque.

Practice problems.

Cooldown Scheduling​

A repeated item may not run again until a cooldown passes. Keep a max-heap of what is ready, park each served item in a queue until its cooldown ends, and when nothing is ready jump the clock to the next release instead of ticking through the gap.

Practice problems.

Greedy with Regret​

Take every item greedily, remember what you took in a heap, and when a constraint breaks, undo the single worst choice so far. The heap is the regret: its top is always the cheapest thing to take back.

import heapq
 
def max_courses(courses):
taken, t = [], 0 # max-heap of durations (negated)
for dur, last in sorted(courses, key=lambda c: c[1]):
heapq.heappush(taken, -dur)
t += dur
if t > last:
t += heapq.heappop(taken) # drop the longest course
return len(taken)
 
print(max_courses([[100, 200], [200, 1300], [1000, 1250], [2000, 3200]]))
# 3

The same shape fits the bridge problem. Walk the heights, put every climb in a min-heap, and once there are more climbs than ladders, pay the smallest climb with bricks:

import heapq
 
def furthest(heights, bricks, ladders):
used = [] # climbs currently on a ladder
for i in range(len(heights) - 1):
d = heights[i + 1] - heights[i]
if d <= 0:
continue
heapq.heappush(used, d)
if len(used) > ladders:
bricks -= heapq.heappop(used) # downgrade the smallest to bricks
if bricks < 0:
return i
return len(heights) - 1
 
print(furthest([4, 2, 7, 6, 9, 14, 12], 5, 1))
# 4

Cost: O(n log n), from the sort or from one push and pop per step. Practice problems.

Best-first Enumeration​

The candidates are too many to list but arrive in a structure where each state's successors are no better than it is. Pop the best state, push its successors, and skip ones you have seen. The k-th pop is the k-th best answer, and you never build the rest.

import heapq
 
def k_smallest_pairs(a, b, k):
h, seen, out = [(a[0] + b[0], 0, 0)], {(0, 0)}, []
while h and len(out) < k:
_, i, j = heapq.heappop(h)
out.append((a[i], b[j]))
for ni, nj in ((i + 1, j), (i, j + 1)):
if ni < len(a) and nj < len(b) and (ni, nj) not in seen:
seen.add((ni, nj))
heapq.heappush(h, (a[ni] + b[nj], ni, nj))
return out
 
print(k_smallest_pairs([1, 7, 11], [2, 4, 6], 4))
# [(1, 2), (1, 4), (1, 6), (7, 2)]

The seen set is the dedupe: without it (1, 1) is reached from both (0, 1) and (1, 0). Cost: O(k log k) time and space, since the heap holds at most about k frontier states. Practice problems.

Heaps in Graphs​

Dijkstra, Prim and A* are the same loop: a heap of frontier entries keyed by cost, pop the cheapest, relax its neighbours. Dijkstra keys by distance from the source, Prim by the single edge that connects a node to the tree, A* by distance plus a heuristic. Decrease-key is lazy again: push a fresh entry and skip the stale one when it surfaces (see Lazy deletion and decrease-key).

import heapq
 
def dijkstra(adj, src):
dist = {src: 0}
h = [(0, src)]
while h:
d, u = heapq.heappop(h)
if d > dist.get(u, float('inf')):
continue # stale entry
for v, w in adj[u]:
if d + w < dist.get(v, float('inf')):
dist[v] = d + w
heapq.heappush(h, (d + w, v))
return dist
 
print(dijkstra({0: [(1, 4), (2, 1)], 1: [], 2: [(1, 2)]}, 0))
# {0: 0, 1: 3, 2: 1}

Cost: O((V + E) log V). The graph pages work these through: Shortest Paths and Bipartite and MST and SCC. Practice problems.

Beyond the binary heap​

d-ary, binomial, Fibonacci and pairing heaps​

The binary heap is the default, not the only heap. Each cousin below trades some simplicity for one cost it does better, and knowing which cost is the whole point.

A d-ary heap gives every node d children instead of two. The tree gets shallower (log_d n levels), so a push or a decrease-key walks fewer levels, while a pop has to scan d children per level. It wins when decrease-key is frequent, as in Dijkstra on a dense graph, and it also packs well into cache lines.

A binomial heap is a forest of small trees whose sizes follow the binary digits of n. Merging two heaps is like adding two binary numbers, so it wins on meld in O(log n), where a binary heap needs O(n).

A Fibonacci heap is a lazy forest that postpones tidying until a pop. That laziness gives O(1) amortized decrease-key, which is the theory behind Dijkstra in O(E + V log V). The constants are heavy and the code is long, so it is rarely faster than a binary heap in practice.

A pairing heap is a single tree with a very simple meld and a two-pass pop. It is simple and fast in practice, and many real implementations pick it over the Fibonacci heap even though its decrease-key bound is harder to prove.

HeapPushPop minDecrease-keyMeldWins at
BinaryO(log n)O(log n)O(log n)O(n)simplicity, array layout
d-aryO(log_d n)O(d log_d n)O(log_d n)O(n)cheap decrease-key, cache
BinomialO(1) amortizedO(log n)O(log n)O(log n)meld
FibonacciO(1)O(log n) amortizedO(1) amortizedO(1)Dijkstra in O(E + V log V) on paper
PairingO(1)O(log n) amortizedO(log n) amortizedO(1)speed in practice

Python ships only the binary heap, as heapq. On a contest, a lazy-deletion binary heap beats all of these.

When a heap is the wrong tool​

A heap answers "best right now, while the set changes". When the question is narrower, something cheaper does it.

  • One-shot k-th largest, no stream: quickselect finds it in O(n) average, against O(n log k) for a size-k heap. 215. Kth Largest Element in an Array is the classic.
  • Top-k frequent with bounded counts: a count is at most n, so bucket sort by count is O(n). 347. Top K Frequent Elements allows it.
  • Window extremes: a monotonic deque is O(n) and drops dominated values at once. See Window Extremes.
  • Order and deletes together: a heap cannot delete an arbitrary value or iterate in order. Use SortedList, as in the comparison table.
  • The minimum once: min(xs) is one O(n) pass. Heapifying first costs the same pass and then buys nothing.
import heapq
nums = [7, 2, 9, 4, 11, 5]
 
def quickselect(a, k): # k-th smallest, 0-indexed, O(n) average
pivot = a[len(a) // 2]
lo = [x for x in a if x < pivot]
eq = [x for x in a if x == pivot]
hi = [x for x in a if x > pivot]
if k < len(lo): return quickselect(lo, k)
if k < len(lo) + len(eq): return pivot
return quickselect(hi, k - len(lo) - len(eq))
 
print(quickselect(nums, len(nums) - 2), heapq.nlargest(2, nums)[-1])
# 9 9

Both lines print the second largest value, 9. The quickselect list version uses O(n) extra space; the in-place partition version needs only O(1) extra, apart from the recursion.

Heaps in the wild​

  • Timers. An event loop needs "which deadline fires next?", which is a min-heap keyed by time. Python's asyncio keeps its scheduled callbacks in a heapq list, and the standard sched module does the same. Large kernels often use a timing wheel instead, because most timers are cancelled before they fire and a wheel inserts and cancels in O(1).
  • Event-driven simulation. The next event is the earliest one in the future. Pop it, process it, push the events it causes.
  • External merge sort. Sort chunks that fit in memory, write them as runs, then merge k runs with a min-heap of each run's head, exactly the K-way Merge pattern, with disk reads instead of lists.
  • Schedulers and routers. Anything that picks the highest-priority job or the cheapest next hop is a heap or a close relative.

Common bugs​

Each bug is either linked to the section whose callout covers it, or explained in one line.

  • Sifting down toward the left child only. Swap with the smaller child, never blindly the left one. See Sift down: pop.
  • Un-orderable payloads on ties. Equal priorities make Python compare the payloads. See Tuples, ties and tiebreakers.
  • Forgetting heapq is min-only. Negate on the way in and again on the way out. See Max-heaps.
  • Peeking a stale top after lazy deletion. h[0] may be an entry you already removed, so pop dead entries off the top before you trust it.
  • Heapifying a copy and pushing to the original. heapify works in place on the list you give it, so a copy is a separate heap: after copy = list(a), heapify(copy), heappush(a, 0), the lists differ ([0, 5, 8, 1, 3] and [1, 3, 8, 5]) and only copy is a heap.
  • Calling heappop on an empty list. It raises IndexError: index out of range, so guard with if h: or size-limit the loop.
  • Forgetting to negate back on the way out. A max-heap built from -x returns -x on pop; use -heappop(h) or the answer has the wrong sign.

Recognize it​

Start from the question at the root. Each leaf links to the section that works the pattern.

Do you need the best element repeatedly while the set changes?
no
One-shot k-th, bounded counts, a window, ordered deletes or a single min each have a cheaper tool.
yes
What shape does the problem have?
keep only the k best of a stream
A size-k heap whose root is the weakest survivor.
combine k sorted sources
A heap of each source head.
the median or a running split
A max-heap for the low half, a min-heap for the high half.
sort by start, track what ends soonest
The top is the next resource to free up.
the best value in a sliding window
Push on entry, discard the top once it slides out.
repeat items with a cooldown
A max-heap of what is ready plus a queue of what is waiting.
take greedily, undo the worst choice
The heap top is the cheapest thing to take back.
the next-best candidate, lazily
Pop the best, push its successors.
shortest path or spanning tree
Dijkstra and Prim pop the cheapest frontier edge.
Which heap pattern?

Where to go next​

  • Range Query Trees - another tree packed into a plain array with index arithmetic, this time for range queries rather than a single running extreme.
  • Tries - the other tree on this shelf that almost never gets drawn with TreeNode pointers in practice.
  • Trees in the Wild - where heaps show up disguised as "priority queue" in scheduling, Dijkstra, and merging.
  • Shortest Paths and Bipartite - Dijkstra, the heap's most famous customer.
  • Greedy and Heap Sweeps - the admit / expire / serve loop on intervals.