Simple Algorithm
Algorithms & Data Structures · Optimized · 22 min

Heaps & Priority Queues

Always know the minimum: sift up, sift down and heapify.

Dijkstra's algorithm, Huffman coding, event-driven simulators and operating-system schedulers all ask one question over and over: which item is the smallest right now? A binary heap answers it instantly and absorbs every insertion or removal in O(log⁡n)O(\log n) steps, using nothing but an array and the arithmetic 2i+12i+1.

What you’ll learn

  • Define the priority-queue ADT and the heap property, and navigate a heap stored in an array: children 2i+12i+1 and 2i+22i+2, parent ⌊(i−1)/2⌋\lfloor (i-1)/2 \rfloor.
  • Implement insert (sift-up) and extract-min (sift-down), prove them correct with invariants, and bound them by ⌊log⁡2n⌋\lfloor\log_2 n\rfloor and 2⌊log⁡2n⌋2\lfloor\log_2 n\rfloor comparisons.
  • Support decrease-key and deletion with a position map, or replace them with lazy deletion when using C++ priority_queue or Python heapq.
  • Build a heap bottom-up in O(n)O(n) time, and sort in place with heapsort in O(nlog⁡n)O(n\log n) worst-case time.
  • Recognize heap problems: repeated minimums or maximums, kk-way merging, top kk, running medians, schedules and simulations.

Priority queues, and a tree inside an array

A priority queue is an abstract data type holding items with keys. Its core operations are insert an item, find-min (look at an item with the smallest key) and extract-min (remove it). Many uses add decrease-key (lower the key of an item already inside), delete an arbitrary item, and meld two queues into one. Unlike a stack or a queue, the order in which items leave depends only on their keys, not on when they arrived.

The obvious implementations each make one operation slow:

Implementationinsertfind-minextract-minNotes
Unsorted arrayO(1)O(1)O(n)O(n)O(n)O(n)scans for the minimum every time
Sorted array, largest firstO(n)O(n)O(1)O(1)O(1)O(1)each insertion shifts elements
Balanced BSTO(log⁡n)O(\log n)O(1)O(1) with a cached minimumO(log⁡n)O(\log n)pointers and rotations; keeps far more order than needed
Binary heapO(log⁡n)O(\log n)O(1)O(1)O(log⁡n)O(\log n)one plain array; built from nn keys in O(n)O(n)
All bounds are worst case. A heap keeps exactly as much order as extract-min needs, and that is why it is cheap.

Completeness means no pointers are needed. Number the nodes level by level, left to right, starting from 0, and store node ii in a[i]a[i]:

children of i: 2i+1 and 2i+2,parent of i: ⌊(i−1)/2⌋.\text{children of } i:\ 2i+1 \text{ and } 2i+2, \qquad \text{parent of } i:\ \lfloor (i-1)/2 \rfloor.

A heap of nn keys has height ⌊log⁡2n⌋\lfloor \log_2 n \rfloor (heights count edges), and its leaves are exactly the indices ⌊n/2⌋\lfloor n/2 \rfloor to n−1n-1. Siblings are unordered: a heap is far from sorted, which is exactly why it is cheaper to maintain than a sorted array.

Check your understanding

A 0-indexed heap holds n=10n = 10 keys. Which indices hold its leaves?

  1. 7, 8 and 9
  2. 4 through 9
  3. 5 through 9
  4. 0 through 4
Show the answer

C. 5 through 9

Index ii has a child exactly when 2i+1≤n−1=92i+1 \le n-1 = 9, that is, when i≤4i \le 4. So indices 0 to 4 are internal and 5 to 9 are leaves: ⌊n/2⌋\lfloor n/2 \rfloor to n−1n-1. Indices 5 and 6 sit one level above 7, 8 and 9, yet have no children, because the last level is only partly filled.

Sift-up and sift-down, and why they work

Both operations first keep the tree complete, then repair the order along a single path:

  • Insert appends the key at index nn, the next free leaf, and sifts it up: while it is smaller than its parent, swap the two.
  • Extract-min saves a[0]a[0], moves the last entry a[n−1]a[n-1] to the root, and sifts it down: while it is larger than its smaller child, swap it with that child.
python
class MinHeap:
    def __init__(self):
        self.a = []                          # a[0] is a minimum

    def push(self, x):                       # O(log n)
        a = self.a
        a.append(x)
        i = len(a) - 1
        while i > 0 and a[i] < a[(i - 1) // 2]:      # sift-up
            p = (i - 1) // 2
            a[i], a[p] = a[p], a[i]
            i = p

    def pop(self):                           # O(log n); heap must be non-empty
        a = self.a
        top, last = a[0], a.pop()
        if a:
            a[0] = last
            i, n = 0, len(a)
            while 2 * i + 1 < n:                     # sift-down
                c = 2 * i + 1
                if c + 1 < n and a[c + 1] < a[c]:
                    c += 1                           # the smaller child
                if a[i] <= a[c]:
                    break
                a[i], a[c] = a[c], a[i]
                i = c
        return top

Sift-down compares the two children with each other, then the smaller one with the node: 2 comparisons per level. Python's heapq module implements the same operations as functions on a plain list.

DerivationWhy the heap property survives
  1. k0≤⋯≤kj⏟stay ≤ x ≤ kj+1≤⋯≤kd−1⏟each moves one level down\underbrace{k_0 \le \cdots \le k_j}_{\text{stay}}\ \le\ x\ \le\ \underbrace{k_{j+1} \le \cdots \le k_{d-1}}_{\text{each moves one level down}}

    Sift-up is insertion sort along one path. Before the insertion, the keys k0,…,kd−1k_0, \dots, k_{d-1} on the path from the root to the new leaf's parent are sorted, by the heap property. Sift-up moves the ones larger than xx one level down the path and drops xx into the gap, so the path stays sorted:

  2. anew[u] ≤ aold[u] ≤ a[c]a_{\text{new}}[u]\ \le\ a_{\text{old}}[u]\ \le\ a[c]

    Edges leaving the path stay in order. A node uu on the path either keeps its key or receives its parent's old key, which is no larger; its children off the path are untouched, so for each such child cc:

  3. a[c]<a[i]  and  a[c]≤a[c′]⟹the invariant holds at ca[c] < a[i]\ \text{ and }\ a[c] \le a[c'] \quad\Longrightarrow\quad \text{the invariant holds at } c

    Sift-down keeps one invariant: every parent–child pair is in order except possibly the current node ii and its children, and ii's parent is no larger than ii's children. If a[i]a[i] is at most its smaller child cc, the heap is whole. Otherwise a[c]a[c] is smaller than a[i]a[i] and than its sibling c′c', so after the swap it fits above both, and only the moved key, now at cc, can be out of order:

  4. insert: ⌊log⁡2n⌋ comparisons,extract-min: 2⌊log⁡2n⌋ comparisons\text{insert: } \lfloor \log_2 n \rfloor \text{ comparisons}, \qquad \text{extract-min: } 2\lfloor \log_2 n \rfloor \text{ comparisons}

    Cost. Each iteration moves one level and the height is ⌊log⁡2n⌋\lfloor\log_2 n\rfloor, so both operations take O(log⁡n)O(\log n) time in the worst case, with at most:

Predict before you look

A heap holds one million keys. At most how many comparisons can inserting one more key make?

Show the answer

19 comparisons

The new key lands at index 10610^6, at depth ⌊log⁡2(106+1)⌋=19\lfloor \log_2(10^6+1) \rfloor = 19, since 219=524,288≤1,000,001<2202^{19} = 524{,}288 \le 1{,}000{,}001 < 2^{20}. Sift-up makes at most one comparison per level: 19. Extract-min may need twice as many, 38. A sorted array would shift up to a million entries for a single insertion.

Changing keys: position maps and lazy deletion

Dijkstra's and Prim's algorithms lower the key of an item that is already in the queue. Sifting it up is easy once you know where it is; finding it is the problem, since a heap cannot be searched faster than O(n)O(n). The fix is a position map: pos[x]\mathrm{pos}[x] is item xx's index in the array, updated on every swap. Then decrease-key costs O(1)O(1) to locate the item plus a sift-up, and deleting an arbitrary item moves the last entry into its slot and sifts that entry up or down.

python
# h: item ids in heap order by key[id]; pos[id]: index of id in h
def swap(h, pos, i, j):
    h[i], h[j] = h[j], h[i]
    pos[h[i]], pos[h[j]] = i, j            # every move updates the map

def sift_up(h, pos, key, i):
    while i > 0 and key[h[i]] < key[h[(i - 1) // 2]]:
        swap(h, pos, i, (i - 1) // 2)
        i = (i - 1) // 2

def decrease_key(h, pos, key, item, k):    # O(log n); needs k <= key[item]
    key[item] = k
    sift_up(h, pos, key, pos[item])

def delete(h, pos, key, item):            # O(log n)
    i = pos[item]
    swap(h, pos, i, len(h) - 1)
    h.pop(); del pos[item]
    if i < len(h):                         # the entry moved into slot i
        sift_up(h, pos, key, i)            # may have to go up or down;
        sift_down(h, pos, key, i)          # at most one call moves it

sift_down is the loop of the previous step written with swap. Each move updates pos in O(1)O(1), so the map costs a constant factor and O(n)O(n) memory. Items must be hashable ids, such as vertex numbers.

Think first Delete the key 60 from the min-heap stored as [1,50,2,60,70,3,4][1, 50, 2, 60, 70, 3, 4]. Which way does the moved entry travel?

The last entry, 4, moves into 60's slot, index 3. Its new parent is 50, at index 1, so it must climb: the heap becomes [1,4,2,50,70,3][1, 4, 2, 50, 70, 3]. The replacement comes from a different subtree, so it can be smaller than its new parent, and that is why delete tries both directions.

Library heaps have no decrease-key:

  • C++ std::priority_queue<T> is a max-heap: top() returns the largest element. For a min-heap, declare priority_queue<T, vector<T>, greater<T>>.
  • Python's heapq keeps a plain list as a min-heap: heappush, heappop, heapify in O(n)O(n), heapreplace. For a max-heap, push negated keys (Python 3.14 added heappush_max and heappop_max). Push tuples (priority, counter, item) so that equal priorities never compare the items themselves.
  • Java's PriorityQueue is a min-heap, and its remove(Object) scans the array in O(n)O(n) time.

The contest idiom is lazy deletion: instead of decreasing a key, push a fresh entry, and when an entry reaches the top, skip it if it is stale.

python
import heapq

def dijkstra(adj, s):                     # adj[u] = [(v, w), ...], w >= 0
    dist = {s: 0}
    pq = [(0, s)]
    while pq:
        d, u = heapq.heappop(pq)
        if d > dist[u]:
            continue                      # stale: u improved after this push
        for v, w in adj[u]:
            nd = d + w
            if v not in dist or nd < dist[v]:
                dist[v] = nd
                heapq.heappush(pq, (nd, v))   # instead of decrease-key
    return dist

Each vertex is processed once, so each edge is relaxed once and the heap receives at most m+1m+1 entries. Every operation costs O(log⁡m)=O(log⁡n)O(\log m) = O(\log n) on a simple graph, where m≤n2m \le n^2: O((n+m)log⁡n)O((n+m)\log n) in all, the bound that decrease-key gives, at the price of O(m)O(m) memory.

Check your understanding

Lazy-deletion Dijkstra pops the entry (7,v)(7, v), but dist[v]=5\mathrm{dist}[v] = 5. What should it do?

  1. Relax vv's outgoing edges using distance 7
  2. Skip the entry: it is stale, and vv was already processed with distance 5
  3. Set dist[v]=7\mathrm{dist}[v] = 7, since that is the value just popped
  4. Push (5,v)(5, v) back onto the heap
Show the answer

B. Skip the entry: it is stale, and vv was already processed with distance 5

The entry was pushed before a shorter path to vv was found. When dist[v]\mathrm{dist}[v] dropped to 5, the entry (5,v)(5, v) was pushed, and since 5<75 < 7 it was popped first, so vv's edges were relaxed with the correct distance. The test d > dist[u] filters the leftover entry out.

Heapify in linear time, and heapsort

To turn nn given keys into a heap you could insert them one by one. That costs O(nlog⁡n)O(n\log n), and the bound is reached when every new key climbs to the root, as when a min-heap receives keys in decreasing order. Heapify (Floyd, 1964) does better. It calls sift-down on every node that has children, from the last one, index ⌊n/2⌋−1\lfloor n/2\rfloor - 1, back to the root. When it reaches node ii, both subtrees of ii are already heaps, which is exactly what sift-down needs.

Heapsort (Williams, 1964) sorts in place with a max-heap: heapify, then repeatedly swap the maximum a[0]a[0] with the last entry of the heap, shrink the heap by one, and sift the new root down. The sorted part grows from the right end of the array.

python
def sift_down(a, i, n):            # max-heap on a[0..n-1]
    while 2 * i + 1 < n:
        c = 2 * i + 1
        if c + 1 < n and a[c + 1] > a[c]:
            c += 1
        if a[i] >= a[c]:
            return
        a[i], a[c] = a[c], a[i]
        i = c

def heapsort(a):                   # in place, O(n log n) worst case
    n = len(a)
    for i in range(n // 2 - 1, -1, -1):      # bottom-up heapify: O(n)
        sift_down(a, i, n)
    for end in range(n - 1, 0, -1):          # move the maximum behind the heap
        a[0], a[end] = a[end], a[0]
        sift_down(a, 0, end)

O(n)O(n) to build, then n−1n-1 sift-downs of O(log⁡n)O(\log n) each: O(nlog⁡n)O(n\log n) in the worst case with O(1)O(1) extra memory. Heapsort is not stable, and its jumps across the array make it slower in practice than quicksort, which is why introsort uses it only as a fallback. The lesson Merge Sort, Quicksort & Heapsort compares the three.

Check your understanding

What happens if heapify runs its sift-downs from index 0 upward instead of from ⌊n/2⌋−1\lfloor n/2\rfloor-1 down to 0?

  1. Nothing changes: any order of sift-downs builds a heap
  2. It still builds a heap, but takes O(nlog⁡n)O(n\log n) time
  3. It can finish with keys out of heap order
  4. It sorts the array instead of merely heapifying it
Show the answer

C. It can finish with keys out of heap order

On [5,4,3,2,1][5, 4, 3, 2, 1], index 0 swaps 5 with 3, giving [3,4,5,2,1][3, 4, 5, 2, 1]; index 1 swaps 4 with 1, giving [3,1,5,2,4][3, 1, 5, 2, 4], and the root 3 now sits above 1. Sift-down at ii assumes both subtrees of ii are already heaps, and only the bottom-up order guarantees that.

Recognizing it

Reach for a heap when a problem keeps asking for an extreme while the set changes:

  • "repeatedly take the smallest (or largest, cheapest, earliest)", with insertions between the removals;
  • several sorted sources to merge, or events to process in time order as new events are scheduled;
  • "the kk largest", "the kk-th largest so far", "the median after each insertion";
  • a greedy algorithm that always takes the cheapest available option: Dijkstra's algorithm, Prim's algorithm, Huffman coding;
  • nn and the number of operations around 10510^5 to 10610^6, so that O(log⁡n)O(\log n) per operation fits and a linear scan per operation does not.
Problem (in brief)Key ideaCost
Merge kk sorted lists holding NN items in totalA min-heap of the kk current heads: pop the smallest, push its successor (multiway merge)O(Nlog⁡k)O(N\log k)
The kk largest items of a stream, or the kk-th largest so farA min-heap of size kk: its root is the bar a newcomer must clear (top-kk)O(nlog⁡k)O(n\log k) time, O(k)O(k) memory
The median after every insertionA max-heap for the lower half, a min-heap for the upper half, sizes within oneO(log⁡n)O(\log n) per insertion, O(1)O(1) per query
The fewest rooms that can host a set of meetingsSort by start time; a min-heap holds the end times of meetings in progress, and its size peaks at the answerO(nlog⁡n)O(n\log n)
Join nn ropes into one, paying the combined length at every join, as cheaply as possibleAlways join the two shortest, Huffman's rule, with a min-heapO(nlog⁡n)O(n\log n)
Five classic heap problems. Event-driven simulation (a heap of future events keyed by time) and task scheduling with cooldowns (run the available task with the most copies left) follow the same pattern.
cpp
#include <queue>
#include <tuple>
#include <vector>
using namespace std;

// Merge k sorted lists of total length N in O(N log k).
vector<int> mergeK(const vector<vector<int>>& lists) {
    using T = tuple<int, int, int>;                  // (value, list, index in list)
    priority_queue<T, vector<T>, greater<T>> pq;      // greater<> makes a min-heap
    for (int j = 0; j < (int)lists.size(); ++j)
        if (!lists[j].empty()) pq.emplace(lists[j][0], j, 0);
    vector<int> out;
    while (!pq.empty()) {
        auto [v, j, i] = pq.top(); pq.pop();          // the smallest head: O(log k)
        out.push_back(v);
        if (i + 1 < (int)lists[j].size()) pq.emplace(lists[j][i + 1], j, i + 1);
    }
    return out;
}

The contest idiom: greater<T> turns std::priority_queue into a min-heap, and tuples compare lexicographically, value first. The heap never holds more than kk entries.

Check your understanding

A stream of 10710^7 scores arrives one at a time. After each one, you must report the 100th highest score so far. Which structure fits best?

  1. A max-heap of every score, popped 100 times per query and refilled
  2. A min-heap holding the 100 highest scores so far
  3. Sorting all the scores after each arrival
  4. A hash set of the scores
Show the answer

B. A min-heap holding the 100 highest scores so far

The root of the size-100 min-heap is exactly the 100th highest score so far. A new score either loses to the root, after one comparison, or replaces it in O(log⁡100)O(\log 100) time. One pass, memory for 100 numbers.

Key takeaways

  • A binary heap is a complete binary tree stored level by level in an array (children 2i+12i+1 and 2i+22i+2, parent ⌊(i−1)/2⌋\lfloor (i-1)/2 \rfloor) in which no parent is larger than its children, so a minimum sits at index 0.
  • Insert sifts up and extract-min moves the last entry to the root and sifts it down: at most ⌊log⁡2n⌋\lfloor\log_2 n\rfloor and 2⌊log⁡2n⌋2\lfloor\log_2 n\rfloor comparisons, O(log⁡n)O(\log n) in the worst case; find-min is O(1)O(1).
  • Decrease-key and delete need a position map. Library heaps lack them, so contest code pushes a new entry and skips stale ones when they surface (lazy deletion).
  • Bottom-up heapify builds a heap in O(n)O(n) with fewer than nn swaps; heapsort then sorts in place in O(nlog⁡n)O(n\log n) worst-case time, but not stably.
  • Signals: the smallest or largest item again and again, kk-way merges, top kk, running medians, events in time order, and greedy algorithms that always take the cheapest option.

Check yourself

In the interactive lesson these are scored with your confidence, and what you miss comes back for review.

Question 1

In a min-heap of n≥2n \ge 2 distinct keys, where can the largest key be?

  1. Always at index n−1n-1, the last entry
  2. In any leaf, that is, at any index from ⌊n/2⌋\lfloor n/2 \rfloor to n−1n-1
  3. Always on the bottom level
  4. Always in the root's right subtree
Show the answer

B. In any leaf, that is, at any index from ⌊n/2⌋\lfloor n/2 \rfloor to n−1n-1

A node with a child is smaller than that child, so the largest key has no children: it is a leaf. Nothing more is forced. In the heap [1,2,9,3][1, 2, 9, 3] it sits at index 2, a leaf one level above the bottom, in the right subtree; in [1,9,2][1, 9, 2] it is in the left subtree.

Question 2

A binary heap of nn items has no position map. What does one decrease-key cost in the worst case?

  1. O(1)O(1): overwrite the key
  2. O(log⁡n)O(\log n): one sift-up
  3. O(log⁡2n)O(\log^2 n): a binary search for the item, then a sift-up
  4. O(n)O(n): the item must first be found by scanning the array
Show the answer

D. O(n)O(n): the item must first be found by scanning the array

The heap property says nothing about where a given key sits, apart from the minimum, so locating the item takes a linear scan; the sift-up afterwards costs only O(log⁡n)O(\log n). A position map, updated on every swap, cuts the search to O(1)O(1).

Question 3

Dijkstra's algorithm with lazy deletion pushes a new heap entry on every successful relaxation. On a simple graph with nn vertices and mm edges, what is its running time?

  1. O(nlog⁡n)O(n\log n), because the heap never holds more than nn entries
  2. O((n+m)log⁡n)O((n+m)\log n): up to m+1m+1 entries, each pushed and popped in O(log⁡m)=O(log⁡n)O(\log m) = O(\log n) time
  3. O(m2)O(m^2), because stale entries must be searched for and removed
  4. O(n+m)O(n+m), because lazy deletion removes the heap's logarithmic cost
Show the answer

B. O((n+m)log⁡n)O((n+m)\log n): up to m+1m+1 entries, each pushed and popped in O(log⁡m)=O(log⁡n)O(\log m) = O(\log n) time

With the stale check, each vertex is processed once, so each edge is relaxed once and at most mm entries, plus the source's, are ever pushed. A simple graph has m≤n2m \le n^2, so log⁡m≤2log⁡n\log m \le 2\log n, and the total is O((n+m)log⁡n)O((n+m)\log n): the same bound as with decrease-key, at the cost of O(m)O(m) memory.

Question 4

A C++ program declares std::priority_queue<int> pq; and pushes 3, 1 and 4. What does pq.top() return?

  1. 1
  2. 3
  3. 4
  4. It depends on the insertion order
Show the answer

C. 4

With the default comparator std::less<int>, std::priority_queue is a max-heap: top() is the largest element. For a min-heap, declare priority_queue<int, vector<int>, greater<int>>. Python's heapq is the opposite, a min-heap.

Question 5

Which of these tasks does a heap not handle efficiently on its own?

  1. Merging kk sorted lists into one sorted list
  2. Keeping the 50 largest values seen in a stream
  3. Reporting the smallest stored value that is at least xx, while values are inserted and deleted
  4. Processing simulation events in order of their timestamps as new events are scheduled
Show the answer

C. Reporting the smallest stored value that is at least xx, while values are inserted and deleted

"Smallest value ≥x\ge x" is a successor query, and a heap cannot search: it only knows its minimum. A balanced BST such as std::set answers it in O(log⁡n)O(\log n). The other three only ever need the current minimum (or, for the top 50, the minimum of a size-50 min-heap).

Go deeper

Further reading

  • T. H. Cormen, C. E. Leiserson, R. L. Rivest & C. Stein, Introduction to Algorithms, 4th ed. (MIT Press, 2022), chapter 6.
  • R. Sedgewick & K. Wayne, Algorithms, 4th ed. (Addison-Wesley, 2011), section 2.4.
  • J. W. J. Williams, "Algorithm 232: Heapsort," Communications of the ACM 7(6) (1964), 347–348.
  • R. W. Floyd, "Algorithm 245: Treesort 3," Communications of the ACM 7(12) (1964), 701.