M21 · Heaps and Priority Queues

Heaps and Priority Queues

A priority queue always hands out the smallest (or largest) element next. The binary heap implements one in a plain array: a complete binary tree stored level by level, where every parent is no larger than its children. Push and pop cost O(log n), peeking costs O(1), and building a heap from n elements costs only O(n).

~45 minIntermediateC# · Python · Java · C++
Curriculum: M21 Heaps and Priority Queues · 2 of 2 lessons available

You will be able to

  • Map between a heap array and its implied complete binary tree with the index formulas parent = (i − 1) / 2 and children = 2i + 1, 2i + 2.
  • State the min-heap property and explain why the minimum is always at index 0.
  • Trace push (append and sift up) and pop (move the last element to the root and sift down), and bound both by the tree height.
  • Explain why bottom-up heapify costs O(n) even though it calls sift down n/2 times.
  • Use PriorityQueue<TElement, TPriority>, heapq, java.util.PriorityQueue and std::priority_queue correctly, including which of them are min-heaps by default.

Helpful before this lesson

  • M03 Big O — Count operations, describe growth, and tell worst-case, average and amortized costs apart.
  • M05 Arrays — Contiguous storage, index arithmetic, and how a dynamic array grows while keeping append cheap.
  • M18 Trees — Tree vocabulary, representations and every traversal, recursive and iterative.

Guidance only. Those modules are planned; the essentials are recapped here.

Visual walkthrough

The interactive visualizer needs JavaScript. The explanation and all four implementations below work without it.

What a priority queue promises

A queue hands out elements in arrival order. A priority queue hands out the element with the smallest key next (a min-priority queue), whatever order they arrived in. The operations:

  • push(x): add an element.
  • peek: look at the smallest element without removing it.
  • pop: remove and return the smallest element.

Schedulers (run the most urgent task), simulations (process the earliest event), Dijkstra's shortest paths and Prim's spanning tree (expand the closest vertex), and "top k" queries all need exactly this. A sorted array gives O(1) pop but O(n) push; an unsorted array gives O(1) push but O(n) pop. A binary heap makes both O(log n).

A tree stored in an array

A binary heap is a complete binary tree: every level is full except possibly the last, which fills from the left. Such a tree needs no pointers. Store it level by level in an array, and the links follow from arithmetic:

parent(i) = (i − 1) / 2      (integer division)
left(i)   = 2i + 1
right(i)  = 2i + 2

Index 0 is the root; indices 1 and 2 are its children; 3 to 6 are the next level; and so on. The lab draws both views at once: the tree on top and the array it really is underneath, with matching index labels. A heap of n elements has ⌊log₂ n⌋ + 1 levels, so 31 elements fill exactly 5 levels.

The heap property

In a min-heap, every parent is less than or equal to each of its children:

items[parent(i)] ≤ items[i]    for every i > 0

Follow any path from the root downward and the values never decrease, so the root holds the minimum. Siblings are not ordered, and the array as a whole is not sorted: [1, 5, 2, 9, 6] is a valid min-heap. A max-heap is the same with ≥ (used by heap sort).

push: append, then sift up

Appending at index n keeps the tree complete, but the new value may be smaller than its parent. Sift up repairs that: while the element is not at the root and is smaller than its parent, swap it with the parent.

Each swap moves the element one level up, so push makes at most ⌊log₂ n⌋ swaps and comparisons: O(log n). The Push and pop preset pushes 8, 5, 9, 2, 7: watch 2 climb from index 3 to the root in two swaps.

pop: move the last element to the root, then sift down

The minimum is at index 0, but removing it would leave a hole at the top. Instead:

  1. Remember items[0] (the answer).
  2. Move the last element into index 0 and shrink the array by one. The tree is complete again.
  3. Sift down the new root: pick the smaller child (the left one on ties); if it is smaller than the element, swap them and continue from the child's index; otherwise stop.

Why the smaller child? It must become the parent of the other child, so it has to be the smaller of the two. Sift down makes at most two comparisons per level and descends at most ⌊log₂ n⌋ levels: O(log n). Peek just reads index 0: O(1).

heapify: O(n), not O(n log n)

Building a heap from n arbitrary values by pushing them one at a time costs O(n log n). Bottom-up heapify does better:

for i = n/2 − 1 down to 0:
    siftDown(i)

Indices n/2 and up are leaves, which are already one-element heaps, so only the first half needs work. Going from the last parent back to the root, each sift down merges two heaps (the subtrees) under a new root.

Why only O(n)? Sift down from a node costs at most its height, and most nodes are low. About n/4 nodes have height 1, n/8 have height 2, n/16 height 3, and so on. The total is at most

n · (1/4 + 2/8 + 3/16 + 4/32 + …) = n · 1 = n swaps,

so heapify does fewer than n swaps and, with at most two comparisons per level visited, fewer than 3n comparisons: O(n). The Heapify preset turns 9 4 7 1 8 2 6 3 5 0 into 0 1 2 3 4 7 6 9 5 8 by sifting only the five non-leaf nodes.

Cost summary

Operation Binary heap Note
peek O(1) index 0
push O(log n) sift up, at most height swaps
pop O(log n) sift down, at most 2 comparisons per level
heapify n elements O(n) bottom-up
search for an arbitrary value O(n) a heap is not a search structure
extra space O(1) beyond the array

The bounds are worst case, not amortized, except that a growing array occasionally resizes.

Equal priorities and stability

A heap is not stable: elements with equal keys do not come out in arrival order. If order among equals matters (first come, first served for equal urgency), make the key unique by adding an increasing sequence number: compare (priority, sequence) pairs. Python's heapq documentation recommends exactly this, which also avoids comparing the payload objects themselves.

Language notes

The four standard libraries all provide an array-backed heap, but they disagree on the default direction. This is the single most common bug.

Language Type Default Max/min the other way Empty pop / peek
C# PriorityQueue<TElement, TPriority> (.NET 6+) min (lowest priority first) pass a reversed IComparer<TPriority> Dequeue/Peek throw InvalidOperationException; TryDequeue/TryPeek return false
Python heapq functions on a list min negate keys; Python 3.14 adds heappush_max, heappop_max, heapify_max heappop raises IndexError
Java java.util.PriorityQueue<E> min (natural ordering) new PriorityQueue<>(Comparator.reverseOrder()) poll/peek return null; remove/element throw NoSuchElementException
C++ std::priority_queue<T> max (with std::less) std::priority_queue<T, std::vector<T>, std::greater<>> top/pop on an empty queue are undefined behaviour

More details worth knowing:

  • C#. Element and priority are separate: Enqueue(element, priority). The documentation describes it as an array-backed quaternary (4-ary) min-heap, not binary; the costs are the same in O-notation. There is no decrease-key. Since .NET 9 a Remove method can take out a specific element, but it has to find it first, which is O(n); on earlier versions there is no way at all. The usual workaround for both is to enqueue again and skip stale entries when they come out. Equal priorities come out in no particular order.
  • Python. heapq is a set of functions over an ordinary list, so heap[0] is the peek. heapify is O(n); heapreplace (pop then push) and heappushpop (push then pop) do two operations with one sift. nsmallest/nlargest solve top-k queries.
  • Java. The iterator and toString show the internal array order, not sorted order. remove(Object) and contains are O(n). The class is not thread-safe; use PriorityBlockingQueue across threads.
  • C++. pop() returns void: read top() first, then pop(). The container adaptor sits on top of std::make_heap, std::push_heap and std::pop_heap, which you can also call directly on a vector; make_heap makes at most 3n comparisons.

The teaching implementation

BinaryHeap is a min-heap over a growable array with an optional comparison (pass a reversed one for a max-heap). Its constructor heapifies initial items bottom-up; Push, Pop and Peek follow the steps above, and popping or peeking an empty heap is an error (an exception in C#, Python and Java, std::underflow_error in C++, so the tests can check it). The shared fixture checks the values returned and the exact heap array after each sequence, so all four languages must make the same swaps. Each is also compared with its language's own priority queue on 500 random sequences of operations.

Common mistakes

  • Assuming std::priority_queue is a min-heap. It is a max-heap by default; use std::greater<> for a min-heap.
  • Sifting down to the left child always, instead of the smaller child: the heap property breaks.
  • Off-by-one parent formula with 0-based arrays: it is (i − 1) / 2, not i / 2 (that is the formula for 1-based arrays, where children are 2i and 2i + 1).
  • Treating the heap array as sorted, or iterating a Java PriorityQueue and expecting order.
  • Building a heap by n pushes when all the data is already there: O(n log n) instead of O(n).

Worked practice

1. In a heap array of 20 elements, what are the parent and children of index 6?

Answer

Parent (6 − 1) / 2 = 2; children 2·6 + 1 = 13 and 2·6 + 2 = 14, both below 20, so both exist.

2. Pop once from the min-heap [1, 3, 2, 7, 4]. What is the array afterwards?

Answer

Return 1. Move the last element, 4, to the root: [4, 3, 2, 7]. Children of index 0 are 3 and 2; the smaller is 2 (index 2), and 2 < 4, so swap: [2, 3, 4, 7]. Index 2 has no children, so stop.

3. You need the 10 largest values from a stream of 10 million numbers. Which heap, and how big?

Answer

A min-heap of size 10. Push each number; whenever the heap grows to 11, pop the minimum. The heap always holds the 10 largest seen so far, at O(log 10) per element and O(10) memory. Its root is the smallest of the current top 10, which is exactly the one to evict.

Summary

  • A binary heap is a complete binary tree stored level by level in an array: parent (i − 1) / 2, children 2i + 1 and 2i + 2.
  • Min-heap property: every parent ≤ its children, so the minimum is at index 0.
  • push sifts up and pop sifts down: O(log n). Peek is O(1). Bottom-up heapify is O(n).
  • C#, Python and Java default to min-heaps; C++'s std::priority_queue defaults to a max-heap.

Full implementation

The binary min-heap in four languages, each checked against one shared fixture of heapify, push, pop and peek sequences (including the exact heap array and errors on an empty heap), and 500 random operation sequences compared with PriorityQueue, heapq, java.util.PriorityQueue and std::priority_queue.

namespace Bekadan.Dsa.Examples.Heaps;
 
/// <summary>
/// Array-backed binary min-heap. Parent of i: (i - 1) / 2; children: 2i + 1, 2i + 2.
/// Push and Pop are O(log n), Peek is O(1), building from n items is O(n).
/// </summary>
public sealed class BinaryHeap<T>
{
    private readonly List<T> _items;
    private readonly Comparison<T> _compare;
 
    public BinaryHeap(Comparison<T>? compare = null) : this([], compare)
    {
    }
 
    /// <summary>Builds a heap from existing items with bottom-up heapify.</summary>
    public BinaryHeap(IEnumerable<T> items, Comparison<T>? compare = null)
    {
        _items = [.. items];
        _compare = compare ?? Comparer<T>.Default.Compare;
        for (int i = _items.Count / 2 - 1; i >= 0; i--) // indices Count/2 and up are leaves
            SiftDown(i);
    }
 
    public int Count => _items.Count;
 
    /// <summary>The heap array, index 0 first (for tests and teaching).</summary>
    public IReadOnlyList<T> Items => _items;
 
    public void Push(T value)
    {
        _items.Add(value); // the next free slot keeps the tree complete
        int i = _items.Count - 1;
        while (i > 0)
        {
            int parent = (i - 1) / 2;
            if (_compare(_items[i], _items[parent]) >= 0)
                break; // not smaller than its parent: done
            (_items[i], _items[parent]) = (_items[parent], _items[i]);
            i = parent;
        }
    }
 
    public T Peek()
    {
        if (_items.Count == 0)
            throw new InvalidOperationException("The heap is empty.");
        return _items[0];
    }
 
    public T Pop()
    {
        if (_items.Count == 0)
            throw new InvalidOperationException("The heap is empty.");
        T top = _items[0];
        int last = _items.Count - 1;
        _items[0] = _items[last]; // the last element fills the hole at the root
        _items.RemoveAt(last);
        if (_items.Count > 0)
            SiftDown(0);
        return top;
    }
 
    private void SiftDown(int i)
    {
        while (true)
        {
            int child = 2 * i + 1;
            if (child >= _items.Count)
                return; // a leaf
            if (child + 1 < _items.Count && _compare(_items[child + 1], _items[child]) < 0)
                child++; // the smaller child (the left one on ties)
            if (_compare(_items[child], _items[i]) >= 0)
                return; // not larger than its children: done
            (_items[i], _items[child]) = (_items[child], _items[i]);
            i = child;
        }
    }
}

Tested on .NET 10 (SDK 10.0.403), C# 14 · examples/csharp/Bekadan.Dsa.Examples/Heaps/BinaryHeap.cs

"""Array-backed binary min-heap.
 
Parent of i: (i - 1) // 2; children: 2i + 1 and 2i + 2. push and pop are
O(log n), peek is O(1), building from n items is O(n). The standard library's
heapq module offers the same operations as functions on a plain list.
"""
 
from collections.abc import Iterable
from typing import Generic, TypeVar
 
T = TypeVar("T")
 
 
class BinaryHeap(Generic[T]):
    def __init__(self, items: Iterable[T] = ()) -> None:
        """Builds a heap from existing items with bottom-up heapify."""
        self._items: list[T] = list(items)
        for i in range(len(self._items) // 2 - 1, -1, -1):  # indices len // 2 and up are leaves
            self._sift_down(i)
 
    def __len__(self) -> int:
        return len(self._items)
 
    def items(self) -> list[T]:
        """A copy of the heap array, index 0 first (for tests and teaching)."""
        return list(self._items)
 
    def push(self, value: T) -> None:
        a = self._items
        a.append(value)  # the next free slot keeps the tree complete
        i = len(a) - 1
        while i > 0:
            parent = (i - 1) // 2
            if not a[i] < a[parent]:
                break  # not smaller than its parent: done
            a[i], a[parent] = a[parent], a[i]
            i = parent
 
    def peek(self) -> T:
        if not self._items:
            raise IndexError("peek from an empty heap")
        return self._items[0]
 
    def pop(self) -> T:
        a = self._items
        if not a:
            raise IndexError("pop from an empty heap")
        top = a[0]
        last = a.pop()
        if a:
            a[0] = last  # the last element fills the hole at the root
            self._sift_down(0)
        return top
 
    def _sift_down(self, i: int) -> None:
        a = self._items
        while True:
            child = 2 * i + 1
            if child >= len(a):
                return  # a leaf
            if child + 1 < len(a) and a[child + 1] < a[child]:
                child += 1  # the smaller child (the left one on ties)
            if not a[child] < a[i]:
                return  # not larger than its children: done
            a[i], a[child] = a[child], a[i]
            i = child

Tested on CPython 3.14.0 · examples/python/dsa_examples/binary_heap.py

package dev.bekadan.dsa.heaps;
 
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.NoSuchElementException;
 
/**
 * Array-backed binary min-heap (with respect to the comparator). Parent of i:
 * (i - 1) / 2; children: 2i + 1, 2i + 2. push and pop are O(log n), peek is
 * O(1), building from n items is O(n).
 */
public final class BinaryHeap<T> {
    private final List<T> items;
    private final Comparator<? super T> comparator;
 
    public BinaryHeap(Comparator<? super T> comparator) {
        this(List.of(), comparator);
    }
 
    /** Builds a heap from existing items with bottom-up heapify. */
    public BinaryHeap(Collection<? extends T> initial, Comparator<? super T> comparator) {
        this.items = new ArrayList<>(initial);
        this.comparator = comparator;
        for (int i = items.size() / 2 - 1; i >= 0; i--) { // indices size/2 and up are leaves
            siftDown(i);
        }
    }
 
    public int size() {
        return items.size();
    }
 
    /** The heap array, index 0 first (for tests and teaching). */
    public List<T> items() {
        return Collections.unmodifiableList(items);
    }
 
    public void push(T value) {
        items.add(value); // the next free slot keeps the tree complete
        int i = items.size() - 1;
        while (i > 0) {
            int parent = (i - 1) / 2;
            if (comparator.compare(items.get(i), items.get(parent)) >= 0) {
                break; // not smaller than its parent: done
            }
            Collections.swap(items, i, parent);
            i = parent;
        }
    }
 
    public T peek() {
        if (items.isEmpty()) {
            throw new NoSuchElementException("The heap is empty.");
        }
        return items.get(0);
    }
 
    public T pop() {
        if (items.isEmpty()) {
            throw new NoSuchElementException("The heap is empty.");
        }
        T top = items.get(0);
        T last = items.remove(items.size() - 1);
        if (!items.isEmpty()) {
            items.set(0, last); // the last element fills the hole at the root
            siftDown(0);
        }
        return top;
    }
 
    private void siftDown(int i) {
        while (true) {
            int child = 2 * i + 1;
            if (child >= items.size()) {
                return; // a leaf
            }
            if (child + 1 < items.size() && comparator.compare(items.get(child + 1), items.get(child)) < 0) {
                child++; // the smaller child (the left one on ties)
            }
            if (comparator.compare(items.get(child), items.get(i)) >= 0) {
                return; // not larger than its children: done
            }
            Collections.swap(items, i, child);
            i = child;
        }
    }
}

Tested on Java 25 (Temurin 25.0.5); also compiles on Java 17 · examples/java/src/main/java/dev/bekadan/dsa/heaps/BinaryHeap.java

#pragma once
 
#include <cstddef>
#include <functional>
#include <stdexcept>
#include <utility>
#include <vector>
 
namespace bekadan::dsa {
 
// Array-backed binary min-heap (with respect to Less). Parent of i: (i - 1) / 2;
// children: 2i + 1, 2i + 2. push and pop are O(log n), top is O(1), building from
// n items is O(n). Note: std::priority_queue with std::less is a MAX-heap.
 
template <typename T, typename Less = std::less<>>
class BinaryHeap {
public:
    explicit BinaryHeap(Less less = {}) : less_(std::move(less)) {}
 
    // Builds a heap from existing items with bottom-up heapify.
    explicit BinaryHeap(std::vector<T> items, Less less = {}) : items_(std::move(items)), less_(std::move(less)) {
        for (std::size_t i = items_.size() / 2; i-- > 0;)  // i = size/2 - 1 down to 0; the rest are leaves
            sift_down(i);
    }
 
    [[nodiscard]] std::size_t size() const noexcept { return items_.size(); }
    [[nodiscard]] bool empty() const noexcept { return items_.empty(); }
 
    // The heap array, index 0 first (for tests and teaching).
    [[nodiscard]] const std::vector<T>& items() const noexcept { return items_; }
 
    void push(T value) {
        items_.push_back(std::move(value));  // the next free slot keeps the tree complete
        std::size_t i = items_.size() - 1;
        while (i > 0) {
            const std::size_t parent = (i - 1) / 2;
            if (!less_(items_[i], items_[parent]))
                break;  // not smaller than its parent: done
            std::swap(items_[i], items_[parent]);
            i = parent;
        }
    }
 
    [[nodiscard]] const T& top() const {
        if (items_.empty())
            throw std::underflow_error("the heap is empty");
        return items_.front();
    }
 
    T pop() {
        if (items_.empty())
            throw std::underflow_error("the heap is empty");
        T result = std::move(items_.front());
        if (items_.size() > 1)
            items_.front() = std::move(items_.back());  // the last element fills the hole at the root
        items_.pop_back();
        if (!items_.empty())
            sift_down(0);
        return result;
    }
 
private:
    void sift_down(std::size_t i) {
        while (true) {
            std::size_t child = 2 * i + 1;
            if (child >= items_.size())
                return;  // a leaf
            if (child + 1 < items_.size() && less_(items_[child + 1], items_[child]))
                ++child;  // the smaller child (the left one on ties)
            if (!less_(items_[child], items_[i]))
                return;  // not larger than its children: done
            std::swap(items_[i], items_[child]);
            i = child;
        }
    }
 
    std::vector<T> items_;
    Less less_;
};
 
}  // namespace bekadan::dsa

Tested on C++23, GCC 15.3 (libstdc++) · examples/cpp/include/bekadan/dsa/binary_heap.hpp

References