Don't memorize the heap — watch values sift up and down. A binary heap is a complete tree where every parent beats its children, so the maximum is always the root. It needs no pointers: it lives in a plain array where node i has children at 2i+1 and 2i+2. Push appends a value and sifts it up; pop takes the root and sifts the gap down. Both in O(log n) — the engine behind priority queues, Dijkstra, and heapsort.
parent ≥ children · max at the root · push sifts up · pop sifts down
HEAP
A complete binary tree with the heap property: every parent outranks its children. Max at the root.
ARRAY-BACKED
No pointers: node i has parent (i−1)/2, children 2i+1 and 2i+2.
PUSH
Append at the end, then sift up: swap with the parent while bigger.
POP
Take the root, move the last leaf up, then sift down past the bigger child.
heap.sim — max-heap · push 10, then pop the max
Ready
The same heap drawn two ways: a tree above, its array below. Every parent is ≥ its children, so the max sits at the root. Press Step to push 10 (sift up), then pop the max (sift down).
node i · parent (i−1)/2 · children 2i+1, 2i+2
9
Max (root)
7
Size
Weak order, strong speed
A heap makes a deliberate trade. It does not fully sort its elements — it only guarantees that each parent outranks its two children. That weak promise is exactly enough to keep the maximum pinned at the root, reachable in O(1), while costing only O(log n) to insert or remove. And because the tree is always complete — every level full except possibly the last, filled left to right — it maps perfectly onto an array with no wasted slots and no pointers. Index arithmetic replaces links: parent at (i−1)/2, children at 2i+1 and 2i+2. Every operation is a short walk along one root-to-leaf path, swapping as it goes.
01
Shape and order
Complete tree (filled left to right) plus the heap property (parent ≥ children). The shape lets it pack into an array.
02
Push = append + sift up
Put the value in the next slot, then swap it upward while it beats its parent. At most the tree height.
03
Pop = root out + sift down
The root is the max. Move the last leaf into the root, shrink, then swap down with the larger child.
04
Peek and build
Peek the max in O(1) — it is a[0]. Heapify an unsorted array bottom-up in O(n).
Peek max
O(1)
Push / pop
O(log n)
Build heap
O(n)
Space
O(n)
This one structure is a priority queue: always serve the best element next. Flip the comparison and it becomes a min-heap. It is the beating heart of Dijkstra and Prim (pull the cheapest edge), of heapsort (pop the max n times), of event simulations and task schedulers, and of top-k selection. Whenever you catch yourself repeatedly asking for the largest or smallest thing in a changing set, reach for a heap.
The picture: one array, read as a tree
The result of pushing 5, 2, 8, 1, 9, 3 into a max-heap. The tree is only a way of reading the array: node i has its children at 2i+1 and 2i+2. The 9 arrived fifth, started in slot 4, and swapped its way up through slot 1 to the root (highlighted).
Worked example, step by step
Start from an empty max-heap and push 5, 2, 8, 1, 9, 3, then pop three times. “Swaps” counts how far the element travelled: up for a push, down for a pop. Everything else is the array itself.
#
Operation
Swaps
Heap array after
Returned
1
push 5
0
[5]
-
2
push 2
0
[5, 2]
-
3
push 8
1
[8, 2, 5]
-
4
push 1
0
[8, 2, 5, 1]
-
5
push 9
2
[9, 8, 5, 1, 2]
-
6
push 3
0
[9, 8, 5, 1, 2, 3]
-
7
pop
1
[8, 3, 5, 1, 2]
9
8
pop
1
[5, 3, 2, 1]
8
9
pop
1
[3, 1, 2]
5
Two things to read off the table. First, the heap is not sorted: after step 6 the array is [9, 8, 5, 1, 2, 3], and 1 sits ahead of 2 and 3. The only promise is parent ≥ child, and that is why pushing the 9 cost two swaps but pushing the 3 cost none, since its parent 5 was already larger. Second, each pop returns the maximum (9, 8, 5 here) by moving the last leaf into the root and letting it sink. The sink path is at most the height of the tree, which for six elements is two. Three pops produced a descending sequence without ever sorting the whole array, and that is exactly what heap sort exploits.
Complexity and trade-offs
Case
Time
Space
Why
Binary heap: push
O(log n)
O(1) extra
One append plus at most one swap per level of a tree of height ⌊log₂ n⌋.
Binary heap: pop / peek
O(log n) / O(1)
O(1) extra
Peek reads slot 0. Pop moves the last leaf to the root and sinks it.
Heapify (build from n items)
O(n)
O(1) in place
Sift down from the last parent to the root. Most nodes are near the leaves and move little.
Unsorted array
O(1) push, O(n) pop-max
O(n)
Fast to add to, slow to extract from: a scan for the maximum every time.
Sorted array
O(n) push, O(1) pop-max
O(n)
The reverse trade: inserting shifts elements to keep the order.
Balanced search tree
O(log n) for all three
O(n)
Also supports search and delete-by-key, but with pointer overhead the heap does not have.
The heap is the compromise: neither operation is the cheapest possible, but neither is ever slow. Building by repeated push costs more than heapify. On the ascending input 1…1023 (the worst case for max-heap pushes) the 1023 pushes made 8194 swaps in total, while heapify made 1013, and 1023 pops from the full heap made 7172. That gap is the difference between O(n log n) and O(n) showing up in a counter. What you give up: a heap cannot find an arbitrary key without scanning, cannot iterate in order, and has no cheap delete-by-value unless you also track each item's index.
Common mistakes
Sinking toward the left child only
When sifting down you must compare against the larger of the two children. On [9, 5, 8, 1, 2], popping the 9 moves the last leaf (2) to the root. Following only the left child gives [5, 2, 8, 1], whose root is 5 although 8 is present. The correct result is [8, 5, 2, 1].
Building the heap from the wrong end
Heapify must run from the last parent down to index 0, so each node's subtrees are already heaps. Running it from index 0 upward on [1, 2, 3, 4, 5, 6, 7] returns [3, 5, 7, 4, 2, 6, 1], which is not a heap. The bottom-up order returns [7, 5, 6, 4, 2, 1, 3].
Editing a key inside the array
Changing a value in place breaks the invariant silently. Set the last slot of [9, 8, 5, 1, 2, 3] to 10 and you have [9, 8, 5, 1, 2, 10]: the next pop returns 9, not 10, because nothing sifted the new value up. After any change of priority, sift the item up or down from its index.
Forgetting that Python’s heapq is a min-heap
heapq.heappop returns the smallest item. For a max-heap, push negated values (or wrapper keys) and negate on the way out. Mixing the two conventions in one program gives a queue that runs lowest-priority-first, with no error.
Ties that compare the payload
Pushing (priority, task) tuples works until two priorities are equal, at which point Python compares the tasks, and raises TypeError if they have no ordering. Add an insertion counter as the second tuple element so the comparison never reaches the payload.
Where this shows up
Shortest-path search
Dijkstra’s algorithm keeps its frontier in a priority queue and repeatedly extracts the nearest unsettled vertex. A* does the same with distance plus a heuristic.
Top-k and streaming
To keep the k largest of a stream, hold a min-heap of size k and replace its root whenever a bigger value arrives. That is O(n log k) time and O(k) memory, with no need to store the stream.
Merging and scheduling
Merging k sorted lists takes the smallest head from a heap of k entries each step. Discrete-event simulators and timer queues take the next-due event from a heap in the same way.
Library defaults
Python’s heapq, C++’s std::priority_queue and Java’s PriorityQueue are all array-backed binary heaps, so the sift-up and sift-down above is what runs when you call them.
SOLVE IT YOURSELF
Solve it: heap sort
This one is yours to write — in Python or TypeScript, running for real in your browser. Edit the stub below, hit Run (or ⌘/Ctrl + Enter), and watch the hidden tests. Stuck? the hints are below and Reveal solution is one click away.
YOUR TASK
Implement heap_sort(nums) using a binary max-heap (no built-in sort). First heapify the array so every parent beats its children, then repeatedly swap the root (the max) to the end and sift the new root down over the shrinking heap. Return the sorted list. O(n log n), in place.
HINTS — 4 IDEAS
In an array heap, node i has children 2i+1 and 2i+2. A sift-down swaps a node with its larger child until it is bigger than both.
Build the heap bottom-up: sift-down every node from index n//2 − 1 down to 0.
Now the max is at index 0. Swap it with the last slot, shrink the heap by one, and sift the new root down.
Repeat until the heap is empty — the array is left sorted ascending.
CPython · WebAssembly✓ Solved
1
1
▶ Watch it explained
Heap and Priority Queue: Time and Space Complexity, From First Principles
Check yourself
1 · In a max-heap, where is the maximum element?
The heap property forces every parent above its children, so the maximum bubbles all the way to the root and is readable in O(1).
2 · For node i in the array, where are its children?
A complete tree maps to an array by these index formulas; the parent of i is (i−1)/2. No pointers needed.
3 · After popping the root, how is the heap restored?
Promoting the last leaf keeps the tree complete; sifting it down against the larger child restores the heap property in O(log n).
Questions
Heap vs binary search tree?
A heap enforces only a weak parent-child order, giving O(1) access to the extreme but no efficient search and no sorted traversal. A BST maintains a full ordering: O(log n) search and an in-order walk that is sorted, but no O(1) min/max. Heaps for priority queues, BSTs for ordered lookups.
Is a priority queue the same as a heap?
A priority queue is the abstract idea — push, peek-best, pop-best. A binary heap is its usual implementation. Other implementations exist (pairing heaps, Fibonacci heaps), but the array-backed binary heap is the workhorse for Dijkstra, Prim, heapsort and top-k.
How do I get a min-heap?
Flip the comparison: keep every parent less than or equal to its children, so the minimum sits at the root. Every operation is identical with the inequality reversed — or just store negated keys in a max-heap.
Two short walks along one path.
Push appends and sifts up; pop promotes the last leaf and sifts down. A weak order, and the best element is always one lookup away.