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.
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 inO(log n), but inserting shifts everything after it, so a push isO(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.
That single restriction has two consequences worth stating plainly, because both are exactly what people expect a heap to not do:
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.
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.
| You have | Formula (0-indexed) | On the array above |
|---|---|---|
index i | itself | index 1 holds 3 |
i's left child | 2*i + 1 | index 3 holds 7 |
i's right child | 2*i + 2 | index 4 holds 8 |
i's parent (i > 0) | (i - 1) // 2 | index 0 holds 1 |
| the last non-leaf index | (n // 2) - 1 | used by heapify - see Building a heap in linear time |
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).
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.
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.
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)pushesxfirst, then pops. It returns the smallest of the heap plusx. Ifxis already<=the root, the heap is not touched at all andxcomes straight back.heapreplace(h, x)pops first, then pushesx. It always returns the old root, even whenxis smaller, then siftsxdown from the root.
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.
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:
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.
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.
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.
O(n log n)always. The build isO(n)and then - 1extractions costO(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
iand2i + 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 beO(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.
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 array | BST | SortedList | Heap | |
|---|---|---|---|---|
| Find the min/max | O(1) | O(log n) average | O(1) | O(1) - it is always the root |
| Remove the min/max | O(n) (shift) | O(log n) average | O(log n) | O(log n), always |
| Search an arbitrary value | O(log n) | O(log n) average | O(log n) | O(n) - no ordering rules out a subtree |
| Insert | O(n) (shift) | O(log n) average, O(n) worst | O(log n) | O(log n), always |
| In-order gives all elements sorted | yes, trivially | yes | yes | no |
| Balance guarantee | n/a | none, unless self-balancing | n/a - a list of bounded-size sorted chunks | always 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 < rightinvariant, 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.
| Function | Cost | Does |
|---|---|---|
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 item | Lazily 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:
nlargest and nsmallest take key=, like sorted. The key picks what
is compared; the original items come back:
Which tool to use depends on how big k is next to n:
k = 1: usemax(it)ormin(it). One pass, no heap, and both takekey=too. Theheapqdocs say the same.ksmall next ton: usenlargest/nsmallest.O(n log k)time andO(k)memory, and it works on a stream you cannot hold in memory.knearn: usesorted(it)[:k]. The heap work approachesn log nanyway, andsortedruns in C with a smaller constant. Theheapqdocs recommendsortedfor largerk.
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.
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).
Max-heaps
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:
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.
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.
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:
The counter also makes ties first in, first out, because earlier pushes get smaller counters:
Two ways to skip the tuple, both of which make the object itself orderable:
- Define
__lt__on a class.heapqonly needs<, so one method is enough. Compare only the priority and ties pop in no promised order: - Use
@dataclass(order=True)and exclude the payload. Fields compare in declaration order, andfield(compare=False)removes the payload from the comparison, so it is never reached even when the other fields tie:
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:
Decrease-key is the same move. To change a task's priority, mark its entry stale and push a fresh one. Running it:
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:
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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:
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.
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).
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.
| Heap | Push | Pop min | Decrease-key | Meld | Wins at |
|---|---|---|---|---|---|
| Binary | O(log n) | O(log n) | O(log n) | O(n) | simplicity, array layout |
| d-ary | O(log_d n) | O(d log_d n) | O(log_d n) | O(n) | cheap decrease-key, cache |
| Binomial | O(1) amortized | O(log n) | O(log n) | O(log n) | meld |
| Fibonacci | O(1) | O(log n) amortized | O(1) amortized | O(1) | Dijkstra in O(E + V log V) on paper |
| Pairing | O(1) | O(log n) amortized | O(log n) amortized | O(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, againstO(n log k)for a size-kheap. 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 isO(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 oneO(n)pass. Heapifying first costs the same pass and then buys nothing.
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
asynciokeeps its scheduled callbacks in aheapqlist, and the standardschedmodule 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 inO(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
kruns 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
heapqis 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.
heapifyworks in place on the list you give it, so a copy is a separate heap: aftercopy = list(a),heapify(copy),heappush(a, 0), the lists differ ([0, 5, 8, 1, 3]and[1, 3, 8, 5]) and onlycopyis a heap. - Calling
heappopon an empty list. It raisesIndexError: index out of range, so guard withif h:or size-limit the loop. - Forgetting to negate back on the way out. A max-heap built from
-xreturns-xon 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.
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
TreeNodepointers 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.