Heaps & Priority Queues
Get the min (or max) in O(1), insert and remove in O(log n) — all stored in a plain array.
A priority queue is an abstract data type: insert items with priorities and always remove the highest-priority one first. The standard implementation is a binary heap.
A min-heap is a complete binary tree where every parent is ≤ its children (in a max-heap, ≥). So the minimum is always at the root.
Stored as an array
Because the tree is complete, it packs into an array with no pointers. For the node at index i (0-based):
Operations
| Operation | How | Time |
|---|---|---|
peek | Return a[0] | O(1) |
push(x) | Append at the end, sift up while smaller than the parent | O(log n) |
pop() | Move the last element to the root, sift down swapping with the smaller child | O(log n) |
heapify(array) | Sift down every internal node, bottom-up | O(n) |
class MinHeap {
private int[] a = new int[16];
private int n = 0;
void push(int x) {
if (n == a.length) a = Arrays.copyOf(a, n * 2);
a[n] = x;
int i = n++;
while (i > 0 && a[(i - 1) / 2] > a[i]) { // sift up
swap(i, (i - 1) / 2);
i = (i - 1) / 2;
}
}
int pop() {
int top = a[0];
a[0] = a[--n];
int i = 0;
while (true) { // sift down
int l = 2 * i + 1, r = l + 1, m = i;
if (l < n && a[l] < a[m]) m = l;
if (r < n && a[r] < a[m]) m = r;
if (m == i) break;
swap(i, m);
i = m;
}
return top;
}
int peek() { return a[0]; }
private void swap(int i, int j) { int t = a[i]; a[i] = a[j]; a[j] = t; }
}
// In practice:
PriorityQueue<Integer> minHeap = new PriorityQueue<>();
PriorityQueue<Integer> maxHeap = new PriorityQueue<>(Comparator.reverseOrder());
PriorityQueue<int[]> byDist = new PriorityQueue<>((p, q) -> Integer.compare(p[1], q[1]));class MinHeap:
def __init__(self):
self.a = []
def push(self, x):
a = self.a
a.append(x)
i = len(a) - 1
while i > 0 and a[(i - 1) // 2] > a[i]: # sift up
a[i], a[(i - 1) // 2] = a[(i - 1) // 2], a[i]
i = (i - 1) // 2
def pop(self):
a = self.a
top, last = a[0], a.pop()
if a:
a[0] = last
i, n = 0, len(a)
while True: # sift down
l, r, m = 2 * i + 1, 2 * i + 2, i
if l < n and a[l] < a[m]: m = l
if r < n and a[r] < a[m]: m = r
if m == i: break
a[i], a[m] = a[m], a[i]
i = m
return top
# In practice: heapq (a min-heap on a plain list)
import heapq
h = []
heapq.heappush(h, 5)
heapq.heappush(h, (2, "task")) # tuples compare by first element
heapq.heappop(h)
heapq.heapify(nums) # O(n)
heapq.heappush(h, -x) # max-heap trick: negate values
heapq.nlargest(3, nums)class MinHeap<T> {
private a: T[] = [];
constructor(private cmp: (x: T, y: T) => number) {}
get size() { return this.a.length; }
peek(): T | undefined { return this.a[0]; }
push(x: T) {
const a = this.a;
a.push(x);
let i = a.length - 1;
while (i > 0) { // sift up
const p = (i - 1) >> 1;
if (this.cmp(a[p], a[i]) <= 0) break;
[a[p], a[i]] = [a[i], a[p]];
i = p;
}
}
pop(): T | 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 (;;) { // sift down
const l = 2 * i + 1, r = l + 1;
let m = i;
if (l < a.length && this.cmp(a[l], a[m]) < 0) m = l;
if (r < a.length && this.cmp(a[r], a[m]) < 0) m = r;
if (m === i) break;
[a[i], a[m]] = [a[m], a[i]];
i = m;
}
}
return top;
}
}
// const pq = new MinHeap<number>((x, y) => x - y);
// JavaScript has no built-in heap — this class is worth memorising for interviews.Why heapify is O(n), not O(n log n)
Sifting down costs the node's height, and most nodes are near the bottom: n/2 leaves cost 0, n/4 cost 1, n/8 cost 2, … The sum converges to O(n).
Heap sort
Heapify the array into a max-heap (O(n)), then repeatedly swap the root to the end and sift down: O(n log n), in place, not stable.
Where heaps are used
- Top-K / k-th largest — keep a min-heap of size k: O(n log k). See Top K elements.
- Merge k sorted lists — a heap of the k current heads. See K-way merge.
- Running median — a max-heap plus a min-heap. See Two heaps.
- Dijkstra and Prim — always expand the closest vertex. See Shortest paths.
- Schedulers and timers — next job by priority or deadline.
- A heap is a complete binary tree in an array with the parent ≤ children invariant.
- peek O(1); push/pop O(log n); heapify O(n).
- Use
PriorityQueue(Java),heapq(Python), or a hand-written class (JS/TS). - Reach for a heap when you repeatedly need the current min/max of a changing set.
QFind the k-th largest element in an unsorted array.medium
A min-heap of size k: push each element and pop when the size exceeds k; the root is the answer. O(n log k) time, O(k) space. Alternatively Quickselect: average O(n), worst O(n²).
QHow would you support decrease-key in a binary heap?hard
Keep a map from item to its array index, update the value, then sift up. Most library heaps lack this, so Dijkstra implementations usually push a duplicate entry with the new distance and skip stale entries when they are popped ("lazy deletion").
QWhy is a heap a better priority queue than a sorted array or BST?medium
A sorted array gives O(1) pop-min but O(n) insert. A balanced BST gives O(log n) for both but with pointer overhead and worse constants. A heap gives O(log n) insert/pop, O(1) peek and O(n) build, in a compact cache-friendly array.