Heaps & Priority Queues

Get the min (or max) in O(1), insert and remove in O(log n) — all stored in a plain array.

Intermediate 3 min readLesson 10 of 16 Interview Q&A

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.

9658732
Min-heap: every parent ≤ its children. The root is the minimum.

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):

parent=⌊i−12⌋left=2i+1right=2i+2\text{parent} = \left\lfloor \frac{i-1}{2} \right\rfloor \qquad \text{left} = 2i+1 \qquad \text{right} = 2i+2
20513293648576
The same heap in level order. The children of index 1 (value 5) are at indices 3 and 4.

Operations

OperationHowTime
peekReturn a[0]O(1)
push(x)Append at the end, sift up while smaller than the parentO(log n)
pop()Move the last element to the root, sift down swapping with the smaller childO(log n)
heapify(array)Sift down every internal node, bottom-upO(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]));

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 ∑hn2h+1⋅h\sum_h \frac{n}{2^{h+1}} \cdot h 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.

InteractiveHeap sort
38
27
43
3
9
82
10
55
19
64
Time: O(n log n)Space: O(1)not stable
comparingswappingpivotsorted
Initial array
1/64

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.
Key takeaways
  • 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.
Interview questions
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.