learn/Data Structures/Heap / Priority Queue
{ } TreeIntermediate interactive

Heap / Priority Queue

Complete binary tree; root is always min/max.

min_heap
size 6
4
13
9
27
18
21
array
4
0
13
1
9
2
27
3
18
4
21
5

A min-heap keeps the smallest value at the root.

How it works

A binary heap is a complete tree where every parent dominates its children (min-heap: smaller; max-heap: larger). Stored compactly in an array, it gives O(1) peek at the extreme and O(log n) insert/extract via sift-up and sift-down.

Mental models

  • Array indexing: children of i are 2i+1 and 2i+2 — no pointers needed.
  • Insert at the end, then bubble up until the heap property holds.
  • Extract swaps root with last, shrinks, then sinks the new root down.

Complexity

Peek min/max
O(1)
Insert
O(log n)sift up
Extract
O(log n)sift down
Build heap
O(n)
Space
O(n)

Reach for it when

  • Dijkstra & A*
  • Top-K problems
  • Event-driven schedulers