Skip to content

How a heap always knows the smallest

Working knowledgeUnder the hood

A priority queue answers "what is the smallest?" in constant time and still accepts new items in logarithmic time. The trick is an ordinary array read as a tree, repaired with one walk up or down after every change.

01 You keep needing the smallest

A job scheduler runs the most urgent job next. A game loop handles the earliest timer next. A route finder expands the nearest place next. Each one asks the same question over and over: what is the smallest item right now? And between questions, items keep arriving and leaving.

The two obvious answers each make one operation slow. A heap makes both cheap by keeping only a little order: enough to know the smallest, and no more.

Unsorted listFind min: O(n)Adding is a cheap append, but every "what is smallest?" scans the whole list.
Sorted listInsert: O(n)The smallest is at the front, but each insert shifts everything after its place to make room.
Binary heapBoth: O(log n)Push and pop each touch one path from root to leaf. Peeking at the smallest is O(1).

02 An array that is secretly a tree

A binary heap is a binary tree with two rules. Shape: every level is full except possibly the last, which fills from the left. Order: in a min-heap, every parent is less than or equal to its children. Nothing is said about left versus right, or about cousins.

The shape rule means the tree never has gaps, so it packs into an array with no wasted slots and no pointers. The root is [0], then its two children, then their four, row by row.

One heap, two views: the tree you reason about and the array it is stored in
Heap as a tree
1[0]
3[1]
5[3]
4[4]
2[2]
8[5]
Heap array · 7 slots
10
31
22
53
44
85
6

Row by row, left to right, the tree reads 1, 3 2, 5 4 8: exactly the array. There are no pointers; the index is the link.

Moving around the tree by index arithmetic (0-based)
From slot iFormulaExample, i = 1
Parent(i - 1) // 20
Left child2 * i + 13
Right child2 * i + 24

Because the tree is always this compact, its height is about log₂ n. Six items need three levels; a million need twenty. Every operation below walks at most one root-to-leaf path, so that height is the whole cost.

03 Push: append, then sift up

To push, put the new value in the next free slot: the end of the array. That keeps the shape. It may break the order, so compare it with its parent and swap while the parent is bigger. This is sift up.

Pushing 5, 3, 8, 1, 4, 2 into a min-heap
Step 1 of 11
Min-heap · array and treeEmpty
  • just appended
  • parent compared
  • moved up by a swap

The heap is empty: an empty array, and so no tree.

none yet push

Each swap moves the new value one level up, and it stops as soon as the parent is not bigger. The worst case is a new minimum, which climbs all the way to the root: about log₂ n swaps.

04 Pop: move the last leaf up, sift down

The smallest value is always at [0]. Taking it out leaves a hole at the top. Filling it with a child would leave a gap lower down, so instead take the last item, which can leave without breaking the shape, and put it in the root. Then push it down, swapping with its smaller child, until neither child is smaller. This is sift down.

Popping twice from [1, 3, 2, 5, 4, 8]
Step 1 of 6
Min-heap · array and tree
10
31
22
53
44
85
1
3
5
4
2
8
Min-heap: every parent ≤ its children
Popped
Empty
  • value sifting down
  • child compared
  • settled
  • just popped

Start from the heap the pushes built. The smallest value is at [0], so reading it is free. Removing it is the work.

6 size

Sift down does two comparisons per level, to find the smaller child, so a pop costs about 2 log₂ n comparisons. Popping everything one by one gives the values in sorted order: that is heapsort.

05 Write it once, then use the library

The two functions are short. The only subtle line is choosing the smaller child in pop.

heap.py
def push(h, x):
h.append(x) # new leaf at the end
i = len(h) - 1
while i > 0:
parent = (i - 1) // 2
if h[parent] <= h[i]:
break # parent is not bigger: rule holds
h[parent], h[i] = h[i], h[parent]
i = parent
def pop(h):
top = h[0]
last = h.pop() # take the last leaf off
if h:
h[0] = last # and drop it in the hole at the root
i = 0
main.py
from heap import push, pop
h = []
for x in [5, 3, 8, 1, 4, 2]:
push(h, x)
print(h)
print(pop(h), pop(h), h)
Text
[1, 3, 2, 5, 4, 8]
1 2 [3, 4, 8, 5]

That is the real output of python3 main.py (Python 3.14), and it matches the traces. In practice, use the standard library. Python's heapq works on a plain list in the same layout and gives the same array here:

with_heapq.py
import heapq
h = []
for x in [5, 3, 8, 1, 4, 2]:
heapq.heappush(h, x)
print(h)
print(heapq.heappop(h), heapq.heappop(h), h)
data = [9, 4, 7, 1]
heapq.heapify(data) # O(n), in place
print(data)
Text
[1, 3, 2, 5, 4, 8]
1 2 [3, 4, 8, 5]
[1, 4, 7, 9]

CPython's heappop sifts down a little differently (it pushes the hole to a leaf first, then sifts up), so on other inputs its array can differ from the hand-written one. Both are valid heaps.

Heaps in the standard libraries
LanguageTypeDefault order
Pythonheapq functions on a listMin. Python 3.14 adds heappush_max and friends; before that, push negated values.
JavaPriorityQueueMin, by natural order or a Comparator.
C++std::priority_queueMax. Pass std::greater for a min-heap.

06 What each operation costs

A binary heap of n items
OperationCostWhy
Peek at the smallestO(1)It is always at [0].
PushO(log n)One sift up along one path.
Pop the smallestO(log n)One sift down along one path.
Build from n items (heapify)O(n)Sift down from the last parent back to the root; most nodes are near the bottom and move little.
Find or remove any other valueO(n)The order rule says nothing about where a value is, so you scan.

The heap's favourite trick is top k. To find the 2nd largest of [3, 2, 1, 5, 6, 4], keep a min-heap of at most 2 items. Push each number; when the heap grows past 2, pop its smallest. What survives are the 2 largest, and the root is the smaller of them.

kth.py
import heapq
def kth_largest(nums, k):
h = [] # min-heap of the k largest seen so far
for x in nums:
heapq.heappush(h, x)
if len(h) > k:
heapq.heappop(h) # drop the smallest of the k + 1
return h[0]
print(kth_largest([3, 2, 1, 5, 6, 4], 2))
Text
5

Each step works on a heap of size k, not n, so the whole pass is O(n log k) and holds only k items. That is how a leaderboard keeps a live top 100 from a stream of millions of scores.

07 When it bites

print(h) # [1, 3, 2, 5, 4, 8]Treating the array as sortedOnly h[0] is guaranteed. The second smallest is h[1] or h[2], and the last slot is not the largest. To read items in order, pop them.
std::priority_queue<int> pq;Assuming every library is a min-heapC++ gives a max-heap by default, Python a min-heap. Check before you port a solution, or the top is the wrong end.
heappush(h, (priority, task_dict))Ties compare the next fieldTuples compare element by element. Two equal priorities make Python compare the dicts and raise TypeError. Put a counter in between: (priority, n, task).
h[3] = 0 # lower a priority in placeChanging a value inside the heapThe order rule is now broken and nothing repairs it. Push a new entry and skip the old one when it comes out, or use a structure with a decrease-key operation.
if x in h:Searching a heapMembership is a linear scan. If you also need lookups, keep a set or dict beside the heap.

08 Check yourself

Question

In the 0-based array layout, where are the children of slot 4?

Question

A min-heap's array is [2, 5, 3, 9, 6, 4]. Which statement must be true?

Question

During pop, the value at the root is bigger than both children, 7 and 4. What does sift down do?

09 Practise this

Was this tutorial useful?Your vote tells us what to improve next.
Spotted a mistake, or something unclear?