A binary heap is a complete binary tree, stored in a plain array, in which every parent is no larger than its children (a min-heap) or no smaller (a max-heap). It does not keep everything sorted; it only guarantees that the best element sits at the root. That weaker promise is cheap to maintain: O(1) peek, O(log n) insert and extract, and O(n) to build from scratch. Heaps are the standard implementation of a priority queue, the engine behind Dijkstra's algorithm, schedulers, top-k queries and merging sorted streams.
Think of it like
An emergency room triage desk
Patients are not seen in arrival order: the most urgent case is always next. The triage nurse does not rank the entire waiting room; they only make sure the most urgent patient is at the front. A new arrival is compared with people ahead of them and moves up only as far as their urgency justifies. Partial order, maintained cheaply, is exactly what a heap provides.
Two invariants: shape and order
- Shape: the tree is complete (see Trees & Binary Trees). Every level is full except possibly the last, which fills from the left.
- Order (min-heap): every node is less than or equal to each of its children. By induction, the root holds the minimum of the whole heap.
- Order is only vertical. Siblings and cousins have no required relationship, so a heap is far from sorted.
Heap
- Parent <= children only
- Minimum in O(1); arbitrary search is O(n)
- Always complete, so height is exactly ⌊log₂ n⌋
- Lives in an array with no pointers
Binary search tree
- Left < node < right across whole subtrees
- Search, floor, ceiling, sorted iteration in O(h)
- Height depends on balancing
- Pointer-based nodes
Stored in an array
Because the tree is complete, its level-order layout has no gaps. Store it in an array and navigate with index arithmetic (0-based): the children of i are at 2i + 1 and 2i + 2, and its parent is at ⌊(i − 1) / 2⌋. No pointers, excellent cache locality, and the array can be sorted in place by Heap Sort.
index: 0 1 2 3 4 5 6
value: 1 3 2 7 4 5 9
1
/ \
3 2 3 and 2 are unordered siblings;
/ \ / \ each parent is <= its children
7 4 5 9Sift-up and sift-down
Every heap operation is built from two repair moves. Each walks a single root-to-leaf path, so each costs O(log n).
- 1
Insert: append
Place the new value in the first free array slot. The shape stays complete, but the new value may be smaller than its parent.
- 2
Sift-up
While the value is smaller than its parent, swap them. It bubbles up until its parent is smaller or it reaches the root.
- 3
Extract-min: take the root
Remember
a[0], then move the last element into the root and shrink the array. Shape is preserved, but the root is probably too large. - 4
Sift-down
While the value is larger than its smaller child, swap with that child. Stop when both children are larger or it reaches a leaf.
| Step | Array | What happened |
|---|---|---|
| Start | [1, 3, 2, 7, 4, 5, 9] | A valid min-heap |
| Push 0 | [1, 3, 2, 7, 4, 5, 9, 0] | Appended at index 7, child of index 3 |
| Sift-up | [1, 3, 2, 0, 4, 5, 9, 7] | 0 < 7: swap with parent |
| Sift-up | [1, 0, 2, 3, 4, 5, 9, 7] | 0 < 3: swap again |
| Sift-up | [0, 1, 2, 3, 4, 5, 9, 7] | 0 < 1: reaches the root |
| Pop | [7, 1, 2, 3, 4, 5, 9] | Return 0; last element 7 moves to the root |
| Sift-down | [1, 7, 2, 3, 4, 5, 9] | Children 1 and 2: swap with the smaller, 1 |
| Sift-down | [1, 3, 2, 7, 4, 5, 9] | Children 3 and 4: swap with 3; 7 is now a leaf |
Building a heap in O(n)
Inserting n items one at a time costs O(n log n). Floyd's bottom-up heapify does better. Leaves are already one-element heaps, so start at the last internal node, ⌊n / 2⌋ − 1, and sift each node down, moving backward to the root. When a node is processed, both of its subtrees are already heaps.
Why linear? A node at height h can sift down at most h levels, and a complete tree has at most ⌈n / 2^(h+1)⌉ nodes at height h. Half the nodes are leaves (zero work), a quarter move at most one level, an eighth at most two, and so on.
Heap height, n = 10⁶
19
⌊log₂ n⌋, always
Bottom-up build
< 10⁶ swaps
O(n)
n separate inserts
≈ 1.8 × 10⁷ swaps
worst case, O(n log n)
The priority-queue API
| Operation | Heap implementation | Cost |
|---|---|---|
push(x) / insert / offer | Append, then sift-up | O(log n) |
pop() / extract-min / poll | Move last to root, then sift-down | O(log n) |
peek() / top / min | Read a[0] | O(1) |
heapify(list) | Floyd's bottom-up build | O(n) |
| Decrease-key at a known index | Lower the value, then sift-up | O(log n) |
| Find or delete an arbitrary value | Linear scan to find it, then sift | O(n) |
Heaps in standard libraries
| Language | Type | Default order | Notes |
|---|---|---|---|
| Python | heapq functions on a list | Min-heap | heappush, heappop, heapify, nlargest. For a max-heap, push negated keys or (-priority, item) tuples. |
| Java | PriorityQueue<E> | Min-heap | Pass Comparator.reverseOrder() for a max-heap. remove(Object) and contains are O(n). |
| C++ | std::priority_queue<T> | Max-heap | For a min-heap use std::priority_queue<int, std::vector<int>, std::greater<int>>. |
| JavaScript / TypeScript | None built in | Write a small array-based heap (below) or use a library. |
Classic heap patterns
Top-k with a heap of size k
To keep the k largest items of a stream, use a min-heap of size k. Push each item; if the heap grows to k + 1, pop the minimum. The heap always holds the k largest seen so far, and its root is the k-th largest. Time O(n log k), memory O(k): it works on a billion-item stream with k = 10.
K-way merge
To merge k sorted lists with N total items, keep one entry per list in a min-heap: (value, list id, position). Pop the smallest, output it, and push the next item from the same list. The heap never exceeds k entries, so the merge costs O(N log k). External sorting, log merging and LSM-tree compaction all rely on this.
Median of a data stream with two heaps
Split the numbers into a lower half and an upper half. Keep the lower half in a max-heap and the upper half in a min-heap, with sizes equal or the lower half one larger. The median is then the top of the max-heap, or the average of both tops.
- 1
Add to the lower half
Push the new number onto the max-heap
low. - 2
Restore the split
Pop
low's maximum and push it onto the min-heaphigh. Now every value inlowis <= every value inhigh. - 3
Rebalance sizes
If
highhas more elements thanlow, movehigh's minimum back tolow. - 4
Read the median
Odd count:
low.top. Even count: the average oflow.topandhigh.top. O(log n) per add, O(1) per query.
d-ary heaps
Nothing forces two children. In a d-ary heap the children of i are at d·i + 1 through d·i + d, and the parent is at ⌊(i − 1) / d⌋. The height drops to log_d n, so sift-up (insert, decrease-key) gets faster, while sift-down (extract) must compare d children per level and gets slower: O(d log_d n).
Complexity
| Operation | Time | Space | Notes |
|---|---|---|---|
| Peek min (or max) | O(1) | O(1) | The root, a[0] |
| Push | O(log n) | O(1) | Sift-up; about O(1) on average for random keys |
| Pop | O(log n) | O(1) | Sift-down along one path |
| Build from n items | O(n) | O(1) | Floyd's bottom-up heapify, in place |
| Search arbitrary value | O(n) | O(1) | No left-right ordering to exploit |
| Top-k of n items | O(n log k) | O(k) | Min-heap of size k for the largest |
| Merge k sorted lists (N items) | O(N log k) | O(k) | One heap entry per list |
A heap of n items needs O(n) space, stored contiguously in an array with no pointers.
Implementation
Array-backed heap with push, pop, peek and O(n) bottom-up construction. The TypeScript version is generic and takes a comparator, so it doubles as a max-heap.
class MinHeap:
def __init__(self, items=None):
self.a = list(items) if items else []
for i in range(len(self.a) // 2 - 1, -1, -1): # Floyd's O(n) build
self._sift_down(i)
def __len__(self):
return len(self.a)
def peek(self):
if not self.a:
raise IndexError("peek from empty heap")
return self.a[0]
def push(self, x) -> None:
self.a.append(x) # keeps the tree complete
self._sift_up(len(self.a) - 1)
def pop(self):
if not self.a:
raise IndexError("pop from empty heap")
top = self.a[0]
last = self.a.pop() # remove the last leaf
if self.a:
self.a[0] = last # move it to the root...
self._sift_down(0) # ...and let it sink
return top
def _sift_up(self, i: int) -> None:
a = self.a
while i > 0:
parent = (i - 1) // 2
if a[i] >= a[parent]:
break
a[i], a[parent] = a[parent], a[i]
i = parent
def _sift_down(self, i: int) -> None:
a, n = self.a, len(self.a)
while True:
smallest = i
left, right = 2 * i + 1, 2 * i + 2
if left < n and a[left] < a[smallest]:
smallest = left
if right < n and a[right] < a[smallest]:
smallest = right
if smallest == i:
return
a[i], a[smallest] = a[smallest], a[i]
i = smallest
h = MinHeap([5, 3, 8, 1, 9, 2])
h.push(0)
print([h.pop() for _ in range(len(h))]) # [0, 1, 2, 3, 5, 8, 9]Key takeaways
- A heap is a complete binary tree with parent <= children (min-heap); the root is the minimum, but the rest is only partially ordered.
- Completeness lets it live in an array: children at
2i + 1and2i + 2, parent at⌊(i − 1) / 2⌋. - Insert sifts up and extract sifts down, each O(log n); peek is O(1).
- Bottom-up heapify builds a heap in O(n) because most nodes are near the bottom and sift down only a little.
- Pattern toolkit: size-k min-heap for top-k largest, one-entry-per-list heap for k-way merge, two heaps for a running median.
- Know your library: Python and Java default to min-heaps, C++
priority_queuedefaults to a max-heap.
Common pitfalls
- Swapping with the larger child during sift-down in a min-heap (or the smaller one in a max-heap).
- Using a max-heap for the k largest elements: you then need all n items in memory. A min-heap of size k is the right tool.
- Forgetting that C++
std::priority_queueis a max-heap by default, or that Python'sheapqhas no max-heap mode. - Expecting the heap's array to be sorted, or iterating a
PriorityQueueand assuming priority order. - Pushing tuples with non-comparable payloads in Python: when priorities tie,
heapqcompares the next field and raisesTypeError. Add a counter as a tiebreaker.
Interview tips
- Whenever a problem says "k largest", "k closest", "next smallest" or "merge sorted", consider a heap first and state the O(n log k) bound.
- Explain why a min-heap finds the k largest: the root is the weakest of the current top k, so it is the one to evict.
- Be ready to prove O(n) heapify with the height-sum argument; it is a common follow-up.
- Mention lazy deletion for decrease-key, and that indexed heaps exist when true decrease-key is required.
Real-world applications
- Dijkstra's shortest paths and Prim's minimum spanning tree pick the next closest vertex from a priority queue.
- Operating-system and job schedulers run the highest-priority or earliest-deadline task next.
- Event-driven simulations and timer wheels process the next event in time order.
- External sorting and LSM-tree compaction merge many sorted runs with a k-way heap merge.
- Huffman coding repeatedly combines the two least frequent symbols.
- Streaming analytics: running medians, top-k trending items and percentiles.
Practice problems
Test yourself
What does it cost to build a heap from n unordered items with bottom-up heapify?
Related topics
Finished this lesson? Track it to see your progress on the roadmap.