Module 8 · Trees and Heaps · Lesson 28 of 40

Heaps and priority queues

Always get the smallest (or biggest) item fast. Python's heapq, and the Top-K pattern.

In this lesson · about 22 minutes

  • Describe the heap rule and how a heap is stored in a list
  • Use heapq.heappush and heappop
  • Solve 'top k' problems with a small heap

At a hospital, the most urgent patient is seen first, not the one who came first. That's a priority queue. The usual way to build one is a heap.

The heap rule

A min-heap is a complete binary tree where every parent is smaller than or equal to its children. So the smallest item is always at the root. (A max-heap is the opposite.)

Stored in a list

Because the tree is complete, we store it in a plain list, level by level. For the item at index i:

  • its children are at 2*i + 1 and 2*i + 2
  • its parent is at (i - 1) // 2

Operations

OperationHowCost
Peek at the smallestLook at index 0O(1)
PushAdd at the end, then sift up: swap with the parent while smallerO(log n)
Pop the smallestMove the last item to the root, then sift down: swap with the smaller child while biggerO(log n)
Build a heap from n itemsheapifyO(n)

Try it · see it work

Min-heap: push and pop

Push 1 and watch it sift up to the root. Then pop and watch the last item sift down.

95723

The same heap stored as a Python list:

20
51
32
93
74

Step 1 of 1A min-heap: every parent is smaller than (or equal to) its children, so the smallest value sits at the root.

heapq in Python

Python's heapq module turns a normal list into a min-heap:

import heapq
h = []
heapq.heappush(h, 5)
heapq.heappush(h, 2)
heapq.heappop(h)      # 2, the smallest

For a max-heap, push negative numbers (-x) and flip the sign when you pop.

The Top-K pattern

"Find the k biggest numbers." Keep a min-heap of size k. Push each number; if the heap grows past k, pop the smallest. At the end, the heap holds the k biggest, and its root is the k-th biggest. This costs O(n log k), much less than sorting everything when k is small.

Heaps also power Dijkstra's shortest path (Module 9), merging many sorted lists, scheduling meetings, and Huffman compression.

Try it: heapq

Exercise

The k-th largest number

Write kth_largest(nums, k) using a min-heap of size k, as in the lesson. Return the k-th largest value.

Code that runs before yours
import heapq

Exercise

Is it a heap?

Write is_min_heap(h) that returns True if the list follows the min-heap rule: every item at index i is ≤ its children at 2*i + 1 and 2*i + 2 (when they exist).

Check your understanding0 of 3 correct

Question 1

1.Where is the smallest item in a min-heap?

Question 2

2.The item at index 4 in a heap list. Where is its parent?

Question 3

3.How do you get a max-heap from Python's heapq?

Quiz score: 0 of 3

Exercises solved: 0 of 2

Tip: answer every quiz question correctly first.

Noviq Academy is free and for learning. This course follows the topics of a set of DSA study notes, rewritten in Noviq's own words with Python examples. Python runs in your own browser with Pyodide; nothing you type is sent to Noviq.