Data Structures & Algorithms · Module 9 · Lesson 11 min read

Heaps & Priority Queues

What is a heap?

A complete binary tree stored in an array where every parent is smaller than its children (a min-heap) or larger (a max-heap). The smallest item is always at index 0.

Children of index i are at 2i + 1 and 2i + 2, so no pointers are needed.

Costs

OperationBig O
Peek at the minO(1)
PushO(log n): the item "bubbles up"
Pop the minO(log n): the last item "sinks down"
Build from n items (heapify)O(n)

Python: heapq (a min-heap)

Python
import heapq
heapq.heappush(h, x)
heapq.heappop(h)
h[0]                    # peek
heapq.heapify(list)     # turn a list into a heap in place
heapq.nlargest(3, data)

For a max-heap, push negative numbers: heappush(h, -x). For priorities, push tuples: (priority, task).

Where heaps are used

  • Priority queues: task schedulers, the emergency room
  • Dijkstra's shortest-path algorithm
  • Top K problems (next lesson)
  • Merging K sorted lists
  • Heap sort
  • The running median (two heaps)

Example

Python
import heapq

# A to-do list where the lowest number is most urgent
tasks = []
heapq.heappush(tasks, (3, "write report"))
heapq.heappush(tasks, (1, "fix production bug"))
heapq.heappush(tasks, (2, "review PR"))
while tasks:
    priority, task = heapq.heappop(tasks)
    print(priority, task)
# 1 fix production bug / 2 review PR / 3 write report

# Max-heap trick: negate values
nums = [5, 1, 8, 3]
max_heap = [-x for x in nums]
heapq.heapify(max_heap)
print(-max_heap[0])                    # 8

# Merge sorted lists
print(list(heapq.merge([1, 4, 7], [2, 5, 8], [3, 6, 9])))
# [1, 2, 3, 4, 5, 6, 7, 8, 9]