Intermediate 8 min

Heaps and priority queues

A priority queue gives you the next item by priority, and a binary heap is one way to store it.

How it works

Look only at parent-child pairs when checking the heap. The lower of a node’s two children is the one to compare during sift-down. Replace the root, swap it with that child if necessary, and repeat. Only one path changes, so repositioning takes at most the height of the heap.

Walk through an example

In a min-heap, every parent is at most its children, so the smallest item is at the root. After removing the root, move the last item to the top and swap it downward until order is restored.

What to watch for

A heap array is only partially ordered. Reading the whole array in index order does not produce a sorted list.

Code example

from heapq import heappush, heappop

heap = []
for priority in [7, 2, 4]:
    heappush(heap, priority)
print(heappop(heap), heap[0])

Check your understanding

Which priority is exposed at the top next?

See the example and explanation
Worked example
Given Add priorities 7, 2, and 4. Remove the minimum.
Answer 4

After removing 2, the smallest remaining priority is 4.

Open practice problem
Next lessonBinary search trees