Always get the biggest (or smallest) item fast. Used for schedulers, top-K and merging sorted streams.
A priority queue hands you the most important item first: the smallest, the largest, the earliest deadline. A heap is the structure that makes it fast. You can add an item and remove the top one in O(log n), and look at the top in O(1).
A normal queue gives you the oldest item first. A priority queue gives you the item with the best priority first, whatever order they arrived in. You could keep a sorted list, but then every insert costs O(n). You could scan for the best each time, but then every removal costs O(n). A heap makes both cheap, by keeping the data only partly sorted.
A binary heap is a complete binary tree: every level is full except maybe the last, which fills from the left. Because of that, it fits neatly into an array. The top of the heap is always at index 0, so peek is instant.
Push: put the new item at the end of the array (the next free spot in the tree), then sift up: while it beats its parent, swap them. Pop: take the root, move the last item into the root, then sift down: while it loses to a child, swap it with the better child. Each moves along one path, and a tree of n items is only about logโ(n) levels tall.
| Operation | What it does | Cost |
|---|---|---|
| peek | Read index 0 | O(1) |
| push | Add at the end, sift up | O(log n) |
| pop | Remove the root, move the last to the root, sift down | O(log n) |
| heapify (build from n items) | Sift down every parent, from the last one back to the root | O(n) |
| decrease-key / update | Change a priority, then sift up or down. Needs to know the index | O(log n) |
| search or delete by value | No order to use, so scan | O(n) |
| Relation | Formula (0-based) | Example for i = 3 |
|---|---|---|
| Parent of i | (i โ 1) / 2, rounded down | 1 |
| Left child of i | 2i + 1 | 7 |
| Right child of i | 2i + 2 | 8 |
| Last parent | n / 2 โ 1, rounded down | for n = 10 it is 4 |
| Kind | Idea | When it matters |
|---|---|---|
| Binary heap | Two children per node | The default. Simple and fast in practice |
| d-ary heap (for example 4-ary) | More children, so a shorter tree | Many decrease-key calls, better cache use |
| Binomial / Fibonacci heap | Cheaper decrease-key in theory | Big graph algorithms. Rarely worth the complexity |
| Timing wheel | Buckets by time slot, not a heap | Millions of timers with O(1) insert |
Numbers to push, in order: 50, 30, 70, 20, 40, 10, 60, 5, 45, 35
The array is not sorted. A heap only promises that every parent is smaller than its children, which is why push and pop move a value along one path only, at most logโ(n) steps. Keep popping to get the numbers in order.
class MinHeap {
a: number[] = [];
push(v: number) {
const a = this.a; a.push(v);
let i = a.length - 1;
while (i > 0) {
const p = (i - 1) >> 1;
if (a[p] <= a[i]) break;
[a[p], a[i]] = [a[i], a[p]]; i = p;
}
}
pop(): number | undefined {
const a = this.a; if (!a.length) return undefined;
const top = a[0], last = a.pop()!;
if (a.length) {
a[0] = last; let i = 0;
for (;;) {
const l = 2 * i + 1, r = l + 1; let m = i;
if (l < a.length && a[l] < a[m]) m = l;
if (r < a.length && a[r] < a[m]) m = r;
if (m === i) break;
[a[i], a[m]] = [a[m], a[i]]; i = m;
}
}
return top;
}
}| Term | Meaning in easy words |
|---|---|
| Priority queue | An abstract queue that returns the best item first |
| Heap | A tree where every parent is ordered against its children |
| Min-heap / max-heap | Smallest / largest item on top |
| Complete binary tree | All levels full except the last, which fills from the left |
| Root | The top node, at index 0 of the array |
| Sift up (bubble up) | Swap a new item upward while it beats its parent |
| Sift down (bubble down) | Swap an item downward with its better child until it fits |
| Heapify | Turn an unsorted array into a heap in O(n) |
| Decrease-key | Improve the priority of an item already in the heap |
| Lazy deletion | Leave stale entries in the heap and skip them when they reach the top |
| Top-K | The K best items out of a large set or stream |
| Tie-break | A second field (such as a counter) to order equal priorities |
| Choice | We gain | We lose |
|---|---|---|
| Heap vs sorted list | Fast inserts | No full order |
| Heap vs balanced tree | Simpler, lower constant cost | No range queries or ordered scan |
| Heap vs timing wheel | Exact order of timers | O(log n) instead of O(1) for huge timer counts |
| Lazy deletion | No index map needed | Heap holds stale items for a while |
| d-ary heap | Fewer levels, better cache use | More comparisons per level |
| One heap vs partitioned heaps | Simplicity | Scale (but global order is lost across partitions) |