TExcelTAD
Home › Data Structures & Algorithms › Heaps & Priority Queues

Heaps & Priority Queues

A priority queue is a queue where items don't leave in arrival order but in order of priority: the most urgent patient in an emergency room, the cheapest unfinished vertex in Dijkstra's algorithm, the next event in a simulation. It supports:

Operation Meaning
push(x) add an item
pop() remove and return the item with the smallest key (min-priority queue)
peek() look at that item without removing it

The standard implementation is a binary heap, which does push and pop in O(log n) and peek in O(1).

The binary min-heap

A binary min-heap is a complete binary tree (all levels full except the last, filled from the left) with the heap property: every parent is smaller than or equal to its children. So the minimum is always at the root. Because the tree is complete, it is stored in a plain array (see Array Implementation of Trees): the children of index i are at 2i + 1 and 2i + 2, the parent at (i - 1) // 2.

  • push: put the new value at the end of the array, then sift up: swap it with its parent while it is smaller.
  • pop: take the root, move the last value to the root, then sift down: swap it with its smaller child while it is larger than that child.

Both walk one path between the root and a leaf, so they take O(log n).

Implementation

python · try it yourself
class MinHeap:
    def __init__(self):
        self.a = []

    def push(self, x):
        a = self.a
        a.append(x)
        i = len(a) - 1
        while i > 0 and a[(i - 1) // 2] > a[i]:          # sift up
            p = (i - 1) // 2
            a[p], a[i] = a[i], a[p]
            i = p

    def pop(self):
        a = self.a
        top = a[0]
        last = a.pop()
        if a:
            a[0] = last
            i = 0
            while True:                                   # sift down
                l, r, s = 2 * i + 1, 2 * i + 2, i
                if l < len(a) and a[l] < a[s]: s = l
                if r < len(a) and a[r] < a[s]: s = r
                if s == i:
                    break
                a[s], a[i] = a[i], a[s]
                i = s
        return top

h = MinHeap()
for x in [7, 3, 9, 1, 5]:
    h.push(x)
    print(f"push {x}: {h.a}")
for _ in range(2):
    print(f"pop -> {h.pop()}: {h.a}")
push 7: [7]
push 3: [3, 7]
push 9: [3, 7, 9]
push 1: [1, 3, 9, 7]
push 5: [1, 3, 9, 7, 5]
pop -> 1: [3, 5, 9, 7]
pop -> 3: [5, 7, 9]

The arrays match the animation step by step. Note that a heap is not sorted: [3, 5, 9, 7] only guarantees that each parent is at most its children.

Python's heapq

The standard library's heapq module implements a min-heap on a normal list. Use tuples (priority, item) to attach data to a priority; ties are broken by the next tuple element.

python · try it yourself
import heapq

tasks = []
heapq.heappush(tasks, (2, "write report"))
heapq.heappush(tasks, (1, "fix production bug"))
heapq.heappush(tasks, (3, "update docs"))
heapq.heappush(tasks, (1, "answer customer"))

print("next:", tasks[0])
while tasks:
    priority, task = heapq.heappop(tasks)
    print(priority, task)

data = [15, 3, 22, 8, 41, 1, 9]
print(heapq.nsmallest(3, data), heapq.nlargest(2, data))
heapq.heapify(data)                 # O(n): turn a list into a heap in place
print(data[0], data)
next: (1, 'answer customer')
1 answer customer
1 fix production bug
2 write report
3 update docs
[1, 3, 8] [41, 22]
1 [1, 3, 9, 8, 41, 22, 15]

Tip: heapq has no max-heap. Push -priority instead and negate it again when popping.

Heap sort

Heap sort sorts in place in O(n log n) with no extra memory. It turns the array into a max-heap (largest at the root), then repeatedly swaps the root to the end of the array and sifts the new root down within the shrinking heap.

python · try it yourself
def sift_down(a, i, size):
    while True:
        l, r, big = 2 * i + 1, 2 * i + 2, i
        if l < size and a[l] > a[big]: big = l
        if r < size and a[r] > a[big]: big = r
        if big == i:
            return
        a[i], a[big] = a[big], a[i]
        i = big

def heap_sort(a):
    n = len(a)
    for i in range(n // 2 - 1, -1, -1):      # build the max-heap bottom-up
        sift_down(a, i, n)
    print("max-heap:", a)
    for end in range(n - 1, 0, -1):
        a[0], a[end] = a[end], a[0]          # move the maximum to its final place
        sift_down(a, 0, end)
        print(f"placed {a[end]:>2}: {a[:end]} | {a[end:]}")
    return a

print(heap_sort([4, 10, 3, 5, 1, 8]))
max-heap: [10, 5, 8, 4, 1, 3]
placed 10: [8, 5, 3, 4, 1] | [10]
placed  8: [5, 4, 3, 1] | [8, 10]
placed  5: [4, 1, 3] | [5, 8, 10]
placed  4: [3, 1] | [4, 5, 8, 10]
placed  3: [1] | [3, 4, 5, 8, 10]
[1, 3, 4, 5, 8, 10]

The max-heap and the final order match the animation. Heap sort is not stable, and in practice it is a little slower than quick sort because it jumps around the array, but its O(n log n) worst case makes it a safety net (introsort falls back to it).

Top-k with a small heap

To find the k largest values in a huge stream, keep a min-heap of size k: its root is the smallest of the current top-k, so any new value larger than the root replaces it. That is O(n log k) time and only O(k) memory:

python · try it yourself
import heapq

def top_k(stream, k):
    heap = []
    for x in stream:
        if len(heap) < k:
            heapq.heappush(heap, x)
        elif x > heap[0]:
            heapq.heapreplace(heap, x)     # pop the root and push x in one step
    return sorted(heap, reverse=True)

scores = [(i * 7919) % 10007 for i in range(10_000)]     # 10,000 different scores
print(top_k(scores, 5))
[10006, 10005, 10004, 10003, 10002]

Summary

Operation Binary heap Sorted list Unsorted list
push O(log n) O(n) O(1)
pop min O(log n) O(1) (from the right end of a descending list) O(n)
peek min O(1) O(1) O(n)
build from n items O(n) O(n log n) O(1)

Test yourself

In a min-heap stored as an array, where is the smallest value?

  1. At the last index
  2. At index 0
  3. In the middle
  4. Anywhere

After popping the root of a heap, which value is moved to the root before sifting down?

  1. The smaller child
  2. The last value in the array
  3. The largest value
  4. A random value

What is the time complexity of push and pop on a binary heap with n items?

  1. O(1)
  2. O(log n)
  3. O(n)
  4. O(n log n)