Skip to content
Visual explainer 3h to learn 4 steps

Binary heaps

Implement an array-based min-heap with sift-up, sift-down and O(n) heapify.

By Invicly Tech, , in Data Structures & Algorithms. About 11 minutes to read.

Topic 28 of 54

In short

A binary heap is a complete binary tree stored in an array where every parent is no larger than its children (for a min-heap). The minimum is always at index 0. Push adds at the end and sifts up, pop moves the last item to the root and sifts down, each in O(log n).

Explained simply

A heap is a tree shape built for one job: always knowing the smallest item (in a min-heap) or the largest item (in a max-heap). The rule is simple: every parent is smaller than or equal to its children. So the smallest item is always at the top.

Unlike a search tree, a heap does not keep everything sorted. The left child can be bigger or smaller than the right child. Only the parent-child order matters. This looser rule is what makes heaps cheap to update.

Heaps are stored in a plain array, not with pointers. The tree is always complete: filled level by level, left to right. That means the children of the item at index i are at 2i + 1 and 2i + 2, and you can find any parent with simple maths.

Adding an item puts it at the end and lets it bubble up while it is smaller than its parent. Removing the top moves the last item to the top and lets it sink down. Both take about log n steps, because the tree is only log n levels tall.

Press Play on a diagram to walk through it one step at a time.

MapMin-heap [1, 3, 2, 7, 4, 5] as a tree
1 (index 0)
  • 3 (index 1)
    • 7 (index 3)
    • 4 (index 4)
  • 2 (index 2)
    • 5 (index 5)
LayersHeapify work by level (n = 15)
  1. 1
    Height 3: 1 node

    Sifts at most 3 levels: up to 3 swaps.

  2. 2
    Height 2: 2 nodes

    Up to 2 swaps each: 4.

  3. 3
    Height 1: 4 nodes

    Up to 1 swap each: 4.

  4. 4
    Height 0: 8 leaves

    No work at all.

  5. 5
    Total

    At most 11 swaps for 15 items: linear.

In depth

Array layout and why the tree stays short

With 0-based indexes, node i has children 2i + 1 and 2i + 2 and parent (i - 1) // 2. Some textbooks use 1-based arrays, where children are 2i and 2i + 1 and the parent is i // 2. Be sure which one your code uses.

Because the tree is complete, n items always form a tree of height floor(log2 n). For one million items that is 19 levels. There are no gaps in the array, no pointers and no wasted memory, and walking down the tree touches memory in a predictable pattern.

Indexes beyond the array show where nodes would be: if 2i + 1 >= n, node i is a leaf. That means the leaves are exactly the second half of the array, indexes n // 2 to n - 1. Only the first n // 2 nodes have children, which matters for heapify.

  • 0-based: children 2i+1, 2i+2; parent (i-1)//2
  • Height floor(log2 n): 19 for one million
  • Leaves are indexes n//2 to n-1

Sift up and sift down, step by step

Push appends the new item at index n, which keeps the tree complete, but may break the heap rule with its parent. Sift up: while the item is smaller than its parent, swap them. It stops at the root at the latest, so at most floor(log2 n) swaps.

Pop removes the root. To keep the tree complete, move the last item into the root, then sift down: compare it with both children and swap with the smaller child if that child is smaller. Choosing the smaller child is essential: swapping with the larger child would put a larger item above a smaller one. Repeat until neither child is smaller. At most floor(log2 n) levels, with two comparisons per level.

A small optimisation used by CPython's heapq: instead of swapping at each step, hold the moving item aside, shift the other items into the hole, and write the item once at the end. heapq's pop even sifts the hole all the way to a leaf first and then sifts up, which saves comparisons on average.

FlowPop from min-heap [1, 3, 2, 7, 4, 5]
  1. 1
    Take root

    Return 1.

  2. 2
    Move last to root

    [5, 3, 2, 7, 4]

  3. 3
    Compare children 3, 2

    Smaller is 2; 5 > 2, swap.

  4. 4
    Now [2, 3, 5, 7, 4]

    5 at index 2 has no children.

  5. 5
    Done

    Valid heap with minimum 2 at the root.

Why bottom-up heapify is O(n)

Pushing n items one by one costs O(n log n). Floyd's bottom-up heapify is faster: call sift-down on every non-leaf node, from index n // 2 - 1 back to 0. When a node is processed, both its subtrees are already heaps, so one sift-down fixes it.

The saving comes from where the work happens. A node at height k sifts down at most k levels. About n/2 nodes are leaves (height 0, no work), about n/4 have height 1, n/8 have height 2, and so on. The total is about n (1/4 + 2/8 + 3/16 + ...), and that series sums to n. So heapify does O(n) work, at most about 2n comparisons.

The intuition: most nodes are near the bottom and cheap to fix. With push-one-by-one, most nodes are also near the bottom, but sift-up moves them towards the far-away root, which is the expensive direction.

  • Sift down indexes n//2 - 1 down to 0
  • Sum over heights of (nodes x height) is O(n)
  • heapq.heapify(list) does this in place

heapq in practice

Python's heapq is a set of functions on an ordinary list, implementing a min-heap. heappush and heappop are O(log n). h[0] peeks at the minimum in O(1). heapify is O(n). heappushpop(h, x) pushes then pops in one efficient step, and heapreplace(h, x) pops then pushes; both are O(log n) and faster than two calls.

For a max-heap, the classic trick is to push negated numbers and negate again when popping. Python 3.14 added max-heap functions such as heapq.heappush_max and heapq.heappop_max, but negation works in every version.

heapq has no decrease-key operation and no way to delete an arbitrary item quickly. The usual workaround is lazy deletion: push a new entry with the updated priority, and when popping, skip entries that are out of date. This is exactly how Dijkstra's algorithm is written with heapq.

  • h[0] is the min; h[1] is not necessarily the second smallest
  • Max-heap: push -x, pop and negate
  • No decrease-key: push again and skip stale entries

Learn it in 4 short steps

About 45m each. Track them with a timer in your plan.

  1. 1
    Map tree positions to array indexes~45m
  2. 2
    Implement push with sift-up~45m
  3. 3
    Implement pop with sift-down~45m
  4. 4
    Build a heap in O(n)~45m

Key points

  • Children of i are 2i+1 and 2i+2; parent is (i-1)//2.
  • Peek O(1); push and pop O(log n).
  • Heapify an array bottom-up in O(n), not O(n log n).
  • A heap is not sorted; only the root is guaranteed minimal.

Key terms

Tap a card to flip it. 0/4 known

Examples

python
def push(h, x):                   # O(log n)
    h.append(x)
    i = len(h) - 1
    while i > 0 and h[(i - 1) // 2] > h[i]:
        p = (i - 1) // 2
        h[i], h[p] = h[p], h[i]; i = p

def pop(h):                       # O(log n), assumes h is non-empty
    h[0], h[-1] = h[-1], h[0]
    top, i = h.pop(), 0
    while (c := 2 * i + 1) < len(h):
        if c + 1 < len(h) and h[c + 1] < h[c]: c += 1
        if h[i] <= h[c]: break
        h[i], h[c] = h[c], h[i]; i = c
    return top

Bottom-up heapify traced

Start with [9, 4, 7, 1, 2, 6, 3]. Non-leaves are indexes 2, 1, 0. Index 2 (value 7) has children 6 and 3: swap with 3, giving [9, 4, 3, 1, 2, 6, 7]. Index 1 (value 4) has children 1 and 2: swap with 1, giving [9, 1, 3, 4, 2, 6, 7]. Index 0 (value 9) swaps with 1, then with 2: [1, 2, 3, 4, 9, 6, 7]. Done in 4 swaps.

python
def sift_down(h, i, n):
    while (c := 2 * i + 1) < n:
        if c + 1 < n and h[c + 1] < h[c]:
            c += 1
        if h[i] <= h[c]:
            break
        h[i], h[c] = h[c], h[i]
        i = c

def heapify(h):
    for i in range(len(h) // 2 - 1, -1, -1):
        sift_down(h, i, len(h))
    return h

print(heapify([9, 4, 7, 1, 2, 6, 3]))  # [1, 2, 3, 4, 9, 6, 7]

A max-heap of tasks with heapq

We want the most urgent task first, where a bigger number means more urgent. heapq is a min-heap, so we store (-priority, order, name). The order counter breaks ties so that equal priorities pop first-in first-out, and Python never has to compare the names. heappushpop adds a task and removes the most urgent in one O(log n) call.

python
import heapq, itertools

h, order = [], itertools.count()
for pri, name in [(2, 'email'), (5, 'outage'), (2, 'lunch'), (3, 'review')]:
    heapq.heappush(h, (-pri, next(order), name))

print(h[0][2])                                  # outage (peek)
print(heapq.heappushpop(h, (-4, next(order), 'deploy'))[2])  # outage
while h:
    print(heapq.heappop(h)[2], end=' ')         # deploy review email lunch

Quick reference

  • 0-based: children 2i+1 and 2i+2, parent (i-1)//2, leaves from n//2
  • Peek O(1); push and pop O(log n); heapify O(n)
  • Sift down swaps with the smaller child in a min-heap
  • heappushpop(h, x) and heapreplace(h, x) beat separate push and pop
  • Max-heap: store -x (or use heappush_max in Python 3.14+)
  • Ties: push (priority, counter, item) so items are never compared
  • No decrease-key in heapq: push a new entry and skip stale ones on pop

Common mistakes

  • Assuming heap[1] is the second smallest.
  • Sifting down towards the larger child in a min-heap.

Quick quiz

Pick an answer to see if you're right and why.

Question 1

1In a 0-based array heap, what are the children of index 4?

Question 2

2What is the time to build a heap from n items with bottom-up heapify?

Question 3

3During sift-down in a min-heap, why swap with the smaller child?

Question 4

4Which statement about h = [1, 5, 2, 9, 6] (a valid min-heap) is true?

0/4 answered

Practice exercises

Try each one yourself first. Use the hint if you get stuck, then compare with the solution.

  1. Exercise 1easy

    Write is_min_heap(a) that checks whether a list satisfies the min-heap property in O(n). Example: [1, 3, 2, 7, 4, 5] is True, [1, 3, 2, 0] is False.

  2. Exercise 2medium

    Write a MaxHeap class with push, pop and peek using heapq and negation. Example: after pushing 3, 10, 5, pop returns 10, then 5.

  3. Exercise 3hard

    Write kth_smallest_matrix(m, k) for an n x n matrix whose rows and columns are sorted ascending, in O(k log n) using a heap. Example: [[1, 5, 9], [10, 11, 13], [12, 13, 15]], k = 8 gives 13.

Check yourself

Answer in your head, reveal, then be honest with yourself.

Feel confident about this topic?

Frequently asked questions

Is a heap the same as heap memory?
No. The heap data structure is a tree-shaped priority structure. Heap memory is the region where a program allocates objects at runtime; the names are unrelated.
Why is heapq a min-heap only?
It was designed that way for simplicity. Use negated keys for a max-heap; Python 3.14 added dedicated max-heap functions as well.
Is a sorted list a valid heap?
Yes. A list sorted in ascending order always satisfies the min-heap property, but a heap does not need to be sorted, which is why it is cheaper to maintain.

Go deeper

ShareXLinkedInWhatsApp