Heaps & Priority Queues
Always know the minimum: sift up, sift down and heapify.
Dijkstra's algorithm, Huffman coding, event-driven simulators and operating-system schedulers all ask one question over and over: which item is the smallest right now? A binary heap answers it instantly and absorbs every insertion or removal in steps, using nothing but an array and the arithmetic .
What you’ll learn
- Define the priority-queue ADT and the heap property, and navigate a heap stored in an array: children and , parent .
- Implement insert (sift-up) and extract-min (sift-down), prove them correct with invariants, and bound them by and comparisons.
- Support decrease-key and deletion with a position map, or replace them with lazy deletion when using C++
priority_queueor Pythonheapq. - Build a heap bottom-up in time, and sort in place with heapsort in worst-case time.
- Recognize heap problems: repeated minimums or maximums, -way merging, top , running medians, schedules and simulations.
Priority queues, and a tree inside an array
A priority queue is an abstract data type holding items with keys. Its core operations are insert an item, find-min (look at an item with the smallest key) and extract-min (remove it). Many uses add decrease-key (lower the key of an item already inside), delete an arbitrary item, and meld two queues into one. Unlike a stack or a queue, the order in which items leave depends only on their keys, not on when they arrived.
The obvious implementations each make one operation slow:
| Implementation | insert | find-min | extract-min | Notes |
|---|---|---|---|---|
| Unsorted array | scans for the minimum every time | |||
| Sorted array, largest first | each insertion shifts elements | |||
| Balanced BST | with a cached minimum | pointers and rotations; keeps far more order than needed | ||
| Binary heap | one plain array; built from keys in |
Completeness means no pointers are needed. Number the nodes level by level, left to right, starting from 0, and store node in :
A heap of keys has height (heights count edges), and its leaves are exactly the indices to . Siblings are unordered: a heap is far from sorted, which is exactly why it is cheaper to maintain than a sorted array.
A 0-indexed heap holds keys. Which indices hold its leaves?
- 7, 8 and 9
- 4 through 9
- 5 through 9
- 0 through 4
Show the answer
C. 5 through 9
Index has a child exactly when , that is, when . So indices 0 to 4 are internal and 5 to 9 are leaves: to . Indices 5 and 6 sit one level above 7, 8 and 9, yet have no children, because the last level is only partly filled.
Sift-up and sift-down, and why they work
Both operations first keep the tree complete, then repair the order along a single path:
- Insert appends the key at index , the next free leaf, and sifts it up: while it is smaller than its parent, swap the two.
- Extract-min saves , moves the last entry to the root, and sifts it down: while it is larger than its smaller child, swap it with that child.
class MinHeap:
def __init__(self):
self.a = [] # a[0] is a minimum
def push(self, x): # O(log n)
a = self.a
a.append(x)
i = len(a) - 1
while i > 0 and a[i] < a[(i - 1) // 2]: # sift-up
p = (i - 1) // 2
a[i], a[p] = a[p], a[i]
i = p
def pop(self): # O(log n); heap must be non-empty
a = self.a
top, last = a[0], a.pop()
if a:
a[0] = last
i, n = 0, len(a)
while 2 * i + 1 < n: # sift-down
c = 2 * i + 1
if c + 1 < n and a[c + 1] < a[c]:
c += 1 # the smaller child
if a[i] <= a[c]:
break
a[i], a[c] = a[c], a[i]
i = c
return topSift-down compares the two children with each other, then the smaller one with the node: 2 comparisons per level. Python's heapq module implements the same operations as functions on a plain list.
Sift-up is insertion sort along one path. Before the insertion, the keys on the path from the root to the new leaf's parent are sorted, by the heap property. Sift-up moves the ones larger than one level down the path and drops into the gap, so the path stays sorted:
Edges leaving the path stay in order. A node on the path either keeps its key or receives its parent's old key, which is no larger; its children off the path are untouched, so for each such child :
Sift-down keeps one invariant: every parent–child pair is in order except possibly the current node and its children, and 's parent is no larger than 's children. If is at most its smaller child , the heap is whole. Otherwise is smaller than and than its sibling , so after the swap it fits above both, and only the moved key, now at , can be out of order:
Cost. Each iteration moves one level and the height is , so both operations take time in the worst case, with at most:
A heap holds one million keys. At most how many comparisons can inserting one more key make?
Show the answer
19 comparisons
The new key lands at index , at depth , since . Sift-up makes at most one comparison per level: 19. Extract-min may need twice as many, 38. A sorted array would shift up to a million entries for a single insertion.
Changing keys: position maps and lazy deletion
Dijkstra's and Prim's algorithms lower the key of an item that is already in the queue. Sifting it up is easy once you know where it is; finding it is the problem, since a heap cannot be searched faster than . The fix is a position map: is item 's index in the array, updated on every swap. Then decrease-key costs to locate the item plus a sift-up, and deleting an arbitrary item moves the last entry into its slot and sifts that entry up or down.
# h: item ids in heap order by key[id]; pos[id]: index of id in h
def swap(h, pos, i, j):
h[i], h[j] = h[j], h[i]
pos[h[i]], pos[h[j]] = i, j # every move updates the map
def sift_up(h, pos, key, i):
while i > 0 and key[h[i]] < key[h[(i - 1) // 2]]:
swap(h, pos, i, (i - 1) // 2)
i = (i - 1) // 2
def decrease_key(h, pos, key, item, k): # O(log n); needs k <= key[item]
key[item] = k
sift_up(h, pos, key, pos[item])
def delete(h, pos, key, item): # O(log n)
i = pos[item]
swap(h, pos, i, len(h) - 1)
h.pop(); del pos[item]
if i < len(h): # the entry moved into slot i
sift_up(h, pos, key, i) # may have to go up or down;
sift_down(h, pos, key, i) # at most one call moves itsift_down is the loop of the previous step written with swap. Each move updates pos in , so the map costs a constant factor and memory. Items must be hashable ids, such as vertex numbers.
Think first Delete the key 60 from the min-heap stored as . Which way does the moved entry travel?
The last entry, 4, moves into 60's slot, index 3. Its new parent is 50, at index 1, so it must climb: the heap becomes . The replacement comes from a different subtree, so it can be smaller than its new parent, and that is why delete tries both directions.
Library heaps have no decrease-key:
- C++
std::priority_queue<T>is a max-heap:top()returns the largest element. For a min-heap, declarepriority_queue<T, vector<T>, greater<T>>. - Python's
heapqkeeps a plain list as a min-heap:heappush,heappop,heapifyin ,heapreplace. For a max-heap, push negated keys (Python 3.14 addedheappush_maxandheappop_max). Push tuples(priority, counter, item)so that equal priorities never compare the items themselves. - Java's
PriorityQueueis a min-heap, and itsremove(Object)scans the array in time.
The contest idiom is lazy deletion: instead of decreasing a key, push a fresh entry, and when an entry reaches the top, skip it if it is stale.
import heapq
def dijkstra(adj, s): # adj[u] = [(v, w), ...], w >= 0
dist = {s: 0}
pq = [(0, s)]
while pq:
d, u = heapq.heappop(pq)
if d > dist[u]:
continue # stale: u improved after this push
for v, w in adj[u]:
nd = d + w
if v not in dist or nd < dist[v]:
dist[v] = nd
heapq.heappush(pq, (nd, v)) # instead of decrease-key
return distEach vertex is processed once, so each edge is relaxed once and the heap receives at most entries. Every operation costs on a simple graph, where : in all, the bound that decrease-key gives, at the price of memory.
Lazy-deletion Dijkstra pops the entry , but . What should it do?
- Relax 's outgoing edges using distance 7
- Skip the entry: it is stale, and was already processed with distance 5
- Set , since that is the value just popped
- Push back onto the heap
Show the answer
B. Skip the entry: it is stale, and was already processed with distance 5
The entry was pushed before a shorter path to was found. When dropped to 5, the entry was pushed, and since it was popped first, so 's edges were relaxed with the correct distance. The test d > dist[u] filters the leftover entry out.
Heapify in linear time, and heapsort
To turn given keys into a heap you could insert them one by one. That costs , and the bound is reached when every new key climbs to the root, as when a min-heap receives keys in decreasing order. Heapify (Floyd, 1964) does better. It calls sift-down on every node that has children, from the last one, index , back to the root. When it reaches node , both subtrees of are already heaps, which is exactly what sift-down needs.
Heapsort (Williams, 1964) sorts in place with a max-heap: heapify, then repeatedly swap the maximum with the last entry of the heap, shrink the heap by one, and sift the new root down. The sorted part grows from the right end of the array.
def sift_down(a, i, n): # max-heap on a[0..n-1]
while 2 * i + 1 < n:
c = 2 * i + 1
if c + 1 < n and a[c + 1] > a[c]:
c += 1
if a[i] >= a[c]:
return
a[i], a[c] = a[c], a[i]
i = c
def heapsort(a): # in place, O(n log n) worst case
n = len(a)
for i in range(n // 2 - 1, -1, -1): # bottom-up heapify: O(n)
sift_down(a, i, n)
for end in range(n - 1, 0, -1): # move the maximum behind the heap
a[0], a[end] = a[end], a[0]
sift_down(a, 0, end)to build, then sift-downs of each: in the worst case with extra memory. Heapsort is not stable, and its jumps across the array make it slower in practice than quicksort, which is why introsort uses it only as a fallback. The lesson Merge Sort, Quicksort & Heapsort compares the three.
What happens if heapify runs its sift-downs from index 0 upward instead of from down to 0?
- Nothing changes: any order of sift-downs builds a heap
- It still builds a heap, but takes time
- It can finish with keys out of heap order
- It sorts the array instead of merely heapifying it
Show the answer
C. It can finish with keys out of heap order
On , index 0 swaps 5 with 3, giving ; index 1 swaps 4 with 1, giving , and the root 3 now sits above 1. Sift-down at assumes both subtrees of are already heaps, and only the bottom-up order guarantees that.
Recognizing it
Reach for a heap when a problem keeps asking for an extreme while the set changes:
- "repeatedly take the smallest (or largest, cheapest, earliest)", with insertions between the removals;
- several sorted sources to merge, or events to process in time order as new events are scheduled;
- "the largest", "the -th largest so far", "the median after each insertion";
- a greedy algorithm that always takes the cheapest available option: Dijkstra's algorithm, Prim's algorithm, Huffman coding;
- and the number of operations around to , so that per operation fits and a linear scan per operation does not.
| Problem (in brief) | Key idea | Cost |
|---|---|---|
| Merge sorted lists holding items in total | A min-heap of the current heads: pop the smallest, push its successor (multiway merge) | |
| The largest items of a stream, or the -th largest so far | A min-heap of size : its root is the bar a newcomer must clear (top-) | time, memory |
| The median after every insertion | A max-heap for the lower half, a min-heap for the upper half, sizes within one | per insertion, per query |
| The fewest rooms that can host a set of meetings | Sort by start time; a min-heap holds the end times of meetings in progress, and its size peaks at the answer | |
| Join ropes into one, paying the combined length at every join, as cheaply as possible | Always join the two shortest, Huffman's rule, with a min-heap |
#include <queue>
#include <tuple>
#include <vector>
using namespace std;
// Merge k sorted lists of total length N in O(N log k).
vector<int> mergeK(const vector<vector<int>>& lists) {
using T = tuple<int, int, int>; // (value, list, index in list)
priority_queue<T, vector<T>, greater<T>> pq; // greater<> makes a min-heap
for (int j = 0; j < (int)lists.size(); ++j)
if (!lists[j].empty()) pq.emplace(lists[j][0], j, 0);
vector<int> out;
while (!pq.empty()) {
auto [v, j, i] = pq.top(); pq.pop(); // the smallest head: O(log k)
out.push_back(v);
if (i + 1 < (int)lists[j].size()) pq.emplace(lists[j][i + 1], j, i + 1);
}
return out;
}The contest idiom: greater<T> turns std::priority_queue into a min-heap, and tuples compare lexicographically, value first. The heap never holds more than entries.
A stream of scores arrives one at a time. After each one, you must report the 100th highest score so far. Which structure fits best?
- A max-heap of every score, popped 100 times per query and refilled
- A min-heap holding the 100 highest scores so far
- Sorting all the scores after each arrival
- A hash set of the scores
Show the answer
B. A min-heap holding the 100 highest scores so far
The root of the size-100 min-heap is exactly the 100th highest score so far. A new score either loses to the root, after one comparison, or replaces it in time. One pass, memory for 100 numbers.
Key takeaways
- A binary heap is a complete binary tree stored level by level in an array (children and , parent ) in which no parent is larger than its children, so a minimum sits at index 0.
- Insert sifts up and extract-min moves the last entry to the root and sifts it down: at most and comparisons, in the worst case; find-min is .
- Decrease-key and delete need a position map. Library heaps lack them, so contest code pushes a new entry and skips stale ones when they surface (lazy deletion).
- Bottom-up heapify builds a heap in with fewer than swaps; heapsort then sorts in place in worst-case time, but not stably.
- Signals: the smallest or largest item again and again, -way merges, top , running medians, events in time order, and greedy algorithms that always take the cheapest option.
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
In a min-heap of distinct keys, where can the largest key be?
- Always at index , the last entry
- In any leaf, that is, at any index from to
- Always on the bottom level
- Always in the root's right subtree
Show the answer
B. In any leaf, that is, at any index from to
A node with a child is smaller than that child, so the largest key has no children: it is a leaf. Nothing more is forced. In the heap it sits at index 2, a leaf one level above the bottom, in the right subtree; in it is in the left subtree.
A binary heap of items has no position map. What does one decrease-key cost in the worst case?
- : overwrite the key
- : one sift-up
- : a binary search for the item, then a sift-up
- : the item must first be found by scanning the array
Show the answer
D. : the item must first be found by scanning the array
The heap property says nothing about where a given key sits, apart from the minimum, so locating the item takes a linear scan; the sift-up afterwards costs only . A position map, updated on every swap, cuts the search to .
Dijkstra's algorithm with lazy deletion pushes a new heap entry on every successful relaxation. On a simple graph with vertices and edges, what is its running time?
- , because the heap never holds more than entries
- : up to entries, each pushed and popped in time
- , because stale entries must be searched for and removed
- , because lazy deletion removes the heap's logarithmic cost
Show the answer
B. : up to entries, each pushed and popped in time
With the stale check, each vertex is processed once, so each edge is relaxed once and at most entries, plus the source's, are ever pushed. A simple graph has , so , and the total is : the same bound as with decrease-key, at the cost of memory.
A C++ program declares std::priority_queue<int> pq; and pushes 3, 1 and 4. What does pq.top() return?
- 1
- 3
- 4
- It depends on the insertion order
Show the answer
C. 4
With the default comparator std::less<int>, std::priority_queue is a max-heap: top() is the largest element. For a min-heap, declare priority_queue<int, vector<int>, greater<int>>. Python's heapq is the opposite, a min-heap.
Which of these tasks does a heap not handle efficiently on its own?
- Merging sorted lists into one sorted list
- Keeping the 50 largest values seen in a stream
- Reporting the smallest stored value that is at least , while values are inserted and deleted
- Processing simulation events in order of their timestamps as new events are scheduled
Show the answer
C. Reporting the smallest stored value that is at least , while values are inserted and deleted
"Smallest value " is a successor query, and a heap cannot search: it only knows its minimum. A balanced BST such as std::set answers it in . The other three only ever need the current minimum (or, for the top 50, the minimum of a size-50 min-heap).
Go deeper
- Heap Construction & d-ary Heaps · Why heapify takes O(n), and choosing the heap’s arity.
- Fibonacci & Pairing Heaps · Decrease-key in O(1) amortized, and the heaps used in practice.
- van Emde Boas Trees & Integer Priority Queues · O(log log U) operations on integer keys.
Further reading
- T. H. Cormen, C. E. Leiserson, R. L. Rivest & C. Stein, Introduction to Algorithms, 4th ed. (MIT Press, 2022), chapter 6.
- R. Sedgewick & K. Wayne, Algorithms, 4th ed. (Addison-Wesley, 2011), section 2.4.
- J. W. J. Williams, "Algorithm 232: Heapsort," Communications of the ACM 7(6) (1964), 347–348.
- R. W. Floyd, "Algorithm 245: Treesort 3," Communications of the ACM 7(12) (1964), 701.