awelgorithms

// learn

Heaps and priority queues

A heap is a tree kept in an array where every parent is smaller than its children (a min-heap) or larger (a max-heap). That one rule keeps the smallest item at the root, so you can read it in O(1) and remove it or add a new item in O(log n).

Updated

A priority queue is what you get from it: a queue that always hands you the most urgent item next. Whenever a problem keeps asking for the smallest, largest, closest or earliest of a changing set (top k, merging sorted lists, Dijkstra, scheduling), a heap is usually the answer.

When to use it

The template

import heapq

def k_largest(nums, k):
    heap = []                       # min-heap of the k largest seen so far
    for x in nums:
        heapq.heappush(heap, x)     # O(log k)
        if len(heap) > k:
            heapq.heappop(heap)     # drop the smallest: not in top k
    return heap                     # heap[0] is the k-th largest

# Python's heapq is a min-heap; push -x for a max-heap.

The variants you will meet

How a heap is stored

A heap is a complete binary tree laid out level by level in an array. For index i the children are at 2i + 1 and 2i + 2 and the parent at (i - 1) // 2, so no pointers are needed.

Insert and extract

Insert appends at the end and sifts the new item up while it beats its parent. Extract moves the last item to the root and sifts it down, swapping with the smaller child, until the order holds again.

Heapify, peek and heap type

Building a heap by sifting down from the last parent to the root takes O(n), not O(n log n). Peeking reads index 0. Flipping the comparison turns a min-heap into a max-heap.

Top k and k-way merge

Keep a heap of size k and evict the worst whenever it grows past k, for O(n log k). To merge k sorted lists, keep each list's current head in a heap and pop the smallest until it is empty.

Time and space complexity

Peek is O(1); insert and extract are O(log n) because sifting walks one root-to-leaf path. Heapify is O(n). Top k over n items is O(n log k) with O(k) space, which beats sorting when k is small. Heap sort is O(n log n) in place.

check which skills you have 10 minutes, free, no account.

All 15 lessons, in order

Common questions

What is the difference between a heap and a priority queue?

A priority queue is the idea: a collection that always gives you the highest-priority item next. A heap is the usual way to build one. In Python, heapq gives you heap functions on a list; in Java, PriorityQueue is a heap underneath.

Min-heap or max-heap for the k largest elements?

A min-heap of size k. Its root is the smallest of the k largest seen so far, so any new item bigger than the root belongs in the top k and the root gets evicted. A max-heap of all n items works too but costs O(n) space.

Why is building a heap O(n) and not O(n log n)?

Sifting down costs the height below a node, and most nodes are near the bottom: half are leaves with no work, a quarter sift one level, and so on. The sum of those costs is bounded by about 2n.

How do I make a max-heap in Python?

heapq only provides a min-heap, so push negated values (-x) and negate again when you pop. For tuples, negate the priority field, for example (-count, word).

Other guides