{ } 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
013
19
227
318
421
5A 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