Data structures

Heaps and priority queues, visualized.

A list that always knows its smallest item. Look at it for free; add or take one in a handful of swaps. Every heap is drawn twice, as a tree and as the list it really is.

What is a heap?

A min-heap is a tree with one rule: every parent ≤ its children. Follow any path down from the top and the numbers never get smaller, so the smallest item has nowhere to be but the very top.

The trick is that the tree is really a plain list. The top is index 0, its two children are 1 and 2, their children are 3 to 6, and so on, row by row. No pointers: the index arithmetic finds everyone. The parent of i is (i − 1) // 2; its children are 2i + 1 and 2i + 2.

A priority queue is the job a heap does: “give me the most urgent thing next”, where urgent means smallest. A hospital triage list, a game’s next event, a route finder’s nearest town. Python’s heapq, Java’s PriorityQueue and C++’s std::priority_queue are all heaps.

01 — one item first

Four pushes and a pop.

The tree and the list are the same heap drawn twice. Watch one number land in both, then climb.

handed back:

Python

def push(heap, x):
heap.append(x)
i = len(heap) - 1
while i > 0:
parent = (i - 1) // 2
if heap[parent] <= heap[i]:
break # rule holds: done
heap[i], heap[parent] = heap[parent], heap[i]
i = parent
def pop(heap):
top = heap[0]
last = heap.pop()
if heap:
heap[0] = last
i, n = 0, len(heap)
while True:
small = i
for c in (2*i + 1, 2*i + 2):
if c < n and heap[c] < heap[small]:
small = c
if small == i:
break # rule holds: done
heap[i], heap[small] = heap[small], heap[i]
i = small
return top
def peek(heap):
return heap[0]

02 — why bother

Find the smallest.

The same seven numbers, kept two ways. A plain list has to check everyone. A heap already did the work.

Unsorted list

looks: 0

Heap

looks: 0

Press the button to find the smallest number in both.

03 — keeping the rule

Sift up, sift down.

A new item joins at the end and climbs while it is smaller than its parent. Taking the top moves the last item up there, and it sinks past its smaller child.

handed back:

A heap of seven. First push 1, then pop the smallest.

04 — your turn

Push, pop, peek.

Your own numbers, up to fifteen. Every button runs the Python on the right, line by line.

handed back:

Pick a value and press a button.

Python

def push(heap, x):
heap.append(x)
i = len(heap) - 1
while i > 0:
parent = (i - 1) // 2
if heap[parent] <= heap[i]:
break # rule holds: done
heap[i], heap[parent] = heap[parent], heap[i]
i = parent
def pop(heap):
top = heap[0]
last = heap.pop()
if heap:
heap[0] = last
i, n = 0, len(heap)
while True:
small = i
for c in (2*i + 1, 2*i + 2):
if c < n and heap[c] < heap[small]:
small = c
if small == i:
break # rule holds: done
heap[i], heap[small] = heap[small], heap[i]
i = small
return top
def peek(heap):
return heap[0]
Each operation ends with its cost here.

05 — the classic bug

Asked for the best, got the worst.

Python’s heapq is a min-heap: heappop always hands back the smallest. Use it for “highest score first” as it is and you get the lowest.

best =

Scores 40, 95, 70, 10. We want the best one first.

Buggy

import heapq
scores = [40, 95, 70, 10]
heap = []
for s in scores:
heapq.heappush(heap, s)
best = heapq.heappop(heap) # 10, not 95

Fixed

import heapq
scores = [40, 95, 70, 10]
heap = []
for s in scores:
heapq.heappush(heap, -s) # flip the sign
best = -heapq.heappop(heap) # 95

Store -score and the smallest stored is the biggest score; flip the sign back when it comes out. More in heapq as a max-heap.

06 — build it in one pass

Heapify.

Got a whole list already? Don’t push items one by one. Start at the last parent and sink every parent, working backwards to the top. Small heaps at the bottom join into bigger ones.

An unsorted list of nine: 9, 6, 8, 2, 7, 1, 5, 4, 3. Read as a tree, it breaks the rule all over.

Python

def heapify(heap):
n = len(heap)
for i in range(n // 2 - 1, -1, -1):
sift_down(heap, i) # the same sink as pop
def sift_down(heap, i):
n = len(heap)
while True:
small = i
for c in (2*i + 1, 2*i + 2):
if c < n and heap[c] < heap[small]:
small = c
if small == i:
return # rule holds: done
heap[i], heap[small] = heap[small], heap[i]
i = small
Time O(n), not O(n log n): half the items are leaves that never move, a quarter can sink one level, an eighth two, and so on. The total stays under about n swaps.

07 — spot them in the wild

Heap or not?

A heap is the answer when you keep asking “what’s next, by priority?”. It is the wrong tool for searching or for listing everything in order.

An emergency room: treat the most urgent patient next

A route finder picking the closest unvisited town next (Dijkstra)

An operating system choosing which waiting job runs next

The top 10 scores out of a million

Showing every contact in A–Z order

Finding a contact by name

08 — the boss level

The 3 largest from a stream.

Numbers arrive one at a time and never stop. Keep the 3 largest so far. The trick sounds backwards: a min-heap of size 3, so the weakest of your top three sits at index 0, first in line to be thrown out.

not kept:

Python

import heapq
def k_largest(stream, k):
heap = [] # the k biggest so far
for x in stream:
if len(heap) < k:
heapq.heappush(heap, x)
elif x > heap[0]: # beats the weakest kept
heapq.heapreplace(heap, x)
return sorted(heap, reverse=True)
Time O(n log k): each number costs at most one sift through a heap of k. Memory O(k): only 3 numbers kept, however long the stream runs. Sorting everything first would need all n in memory.

09 — cheat sheet

Heap time complexity.

Fast at one question, “what is the smallest?”, and cheap to keep that way.

JobCostIn Python (import heapq)
Peek at the smallestO(1)heap[0]
PushO(log n)one swap per level, and there are about log₂ n levelsheapq.heappush(heap, x)
Pop the smallestO(log n)one swap per level, about log₂ n levelsheapq.heappop(heap)
Build from a listO(n)in place, bottom-upheapq.heapify(items)
k largest / smallestO(n log k)heapq.nlargest(k, items), heapq.nsmallest(k, items)
Largest firstO(log n)push -x and flip the sign when it comes out (works on every version); Python 3.14+ also has heappush_max / heappop_max
Find any value, or list in orderO(n)a heap only knows its topuse a set or dict to find, sorted() to list

In other languages

LanguageDefaultPush · pop · peekThe other way round
Python heapqmin-heapheappush · heappop · heap[0]store -x, or heappush_max / heappop_max in 3.14+
Java PriorityQueuemin-heapoffer · poll · peeknew PriorityQueue<>(Collections.reverseOrder())
C++ std::priority_queuemax-heappush · pop (returns nothing) · toppriority_queue<int, vector<int>, greater<int>>
Back a lessonBinary treesUp nextGraphs, BFS and DFS