What's happening?
- Insert adds the value at the end, then swaps it up while it is smaller than its parent.
- Extract-min takes the top, moves the last value to the top, then swaps it down with its smaller child.
- The children of position i live at 2i+1 and 2i+2 — no pointers needed.
Complexity
- Time
- O(log n) insert and extract-min · O(1) to look at the minimum
- Space
- O(n)
Where you'll meet it
Priority queues: task schedulers, Dijkstra's shortest path, "top K" problems, merging sorted streams, and heap sort.
Common mistake
Expecting the array to be sorted. A heap only guarantees each parent ≤ its children — siblings can be in any order.
FAQ
Heap vs binary search tree?
A heap only knows where the smallest value is; a BST keeps everything in order. Heaps are simpler and faster for "give me the minimum".
Why store a tree in an array?
A heap is always a complete tree, so positions map neatly to indexes — it is compact and cache-friendly.
What is a max-heap?
The same with the order flipped: the largest value is at the top.