Algorithms Playbook
Data structureTime O(log n)/op · Space O(n)8 min read

Heaps and priority queues: always know the smallest

How a binary heap stores a complete tree in a plain array, why push and pop cost O(log n), and when a heap beats sorting.

In short

A heap keeps the smallest (min-heap) or largest (max-heap) item at the root, and every parent is ≤ its children. Reading the top is O(1); push and pop are O(log n). It's the data structure behind a priority queue.

A tree stored in an array

A heap is a complete binary tree (every level full except maybe the last, filled left to right), so it fits in an array with no pointers: the children of index i are 2i+1 and 2i+2, and its parent is (i−1)//2.

Min-heap: push and pop
Speed
0∅
1def push(h, x):
2 h.append(x)
3 i = len(h) - 1
4 while i > 0 and h[(i - 1) // 2] > h[i]:
5 h[(i - 1) // 2], h[i] = h[i], h[(i - 1) // 2]
6 i = (i - 1) // 2
7
8def pop(h):
9 top = h[0]
10 h[0] = h[-1]; h.pop()
11 i = 0
12 while True:
13 c = smaller_child(h, i)
14 if c is None or h[i] <= h[c]: break
15 h[i], h[c] = h[c], h[i]
16 i = c
17 return top
A min-heap keeps the smallest value at the root, and every parent ≤ its children. It lives in an array: the children of i are 2i+1 and 2i+2.

Variables

size0
Step 1/27· Swaps: 0
Push and pop cost O(log n) (the height of the tree); reading the minimum is O(1). A heap is a priority queue.
  • Push: add at the end, then sift up while smaller than the parent.
  • Pop: take the root, move the last element to the root, then sift down, swapping with the smaller child.
  • Both walk one root-to-leaf path: the height is log n, hence O(log n).

When to use a heap

NeedStructureCost
Repeatedly the min or max of a changing setHeapO(log n) per op
Min or max of a fixed array, onceA single scanO(n)
Everything in orderSortO(n log n)
Min and max, or any element by valueBalanced BST / sorted structureO(log n)
  • Python: heapq is a min-heap on a list. For a max-heap, push negated values.
  • Java: PriorityQueue is a min-heap; pass Collections.reverseOrder() for a max-heap.
  • TypeScript: no built-in; write a small class or use a library.
  • Building a heap from n items is O(n) with heapify, cheaper than n pushes.

Key takeaways

  • 01A heap is a complete tree in an array; parent (i−1)//2, children 2i+1 and 2i+2.
  • 02Peek O(1); push and pop O(log n).
  • 03Python's heapq is a min-heap: negate values for a max-heap.
  • 04Use a heap when you repeatedly need the best remaining item.

Check your understanding

1 of 3

Cost of reading the smallest element of a min-heap?

Related topics