Heap properties
easy 16 minA binary heap is a complete binary tree in which every parent is greater than or equal to its children (max-heap) or less than or equal to them (min-heap).
Video lesson · Chapter 1 of 5
A portrait with a rule
Heap properties — The firefly chandelier
1:27Reel
Read caption
Yara hangs six numbered lanterns in a complete max-heap and checks why the brightest is always at its root. Fill left to right. Let every parent outshine its children.
How it works
Step through the idea, or press Play.
Shape: a complete tree. Every level is full except possibly the last, which fills from the left with no gaps
Understand it
Start here
What a heap is
A binary heap is a binary tree that obeys two rules at once. The shape rule: it is a complete binary tree. The order rule: every parent is at least as big as its children (a max-heap) or at most as big (a min-heap). Together they put the largest or smallest value at the root, where you can read it in , and they keep the tree so short that adding or removing a value costs only .
Complete shape
Levels fill top to bottom, left to right. No holes, so it fits in an array.
Heap order
Parent children (max-heap) or parent children (min-heap), on every edge.
Extreme at the root
The max or min is always
heap[0]: an peek.Short and wide
Height : 19 levels for a million values.
Rule 1
Shape: a complete binary tree
A complete binary tree has every level completely filled except possibly the last, and the last level is filled from left to right. A new node may only go into the leftmost free slot of the bottom level; if that level is full, it starts a new level on the far left. Level holds at most nodes.
Is this tree complete?
None) ever appears before a real value, the tree is not complete.Complete: [10, 5, 3, 4, 1]
- Root 10, children 5 and 3
- 4 and 1 fill the bottom level from the left
- Array has no gaps: 5 slots, 5 values
Not complete: [10, 5, 3, _, 1]
- Same top two levels
- Slot 3 (left child of 5) is empty but slot 4 is not
- The array has a hole, so it is not a heap
Rule 2
Order: max-heap and min-heap
The order rule compares each node only with its own parent. In a max-heap the parent is never smaller; in a min-heap it is never larger. Because this holds on every edge, it chains all the way up: any value is bounded by every ancestor, so the root is the extreme.
The heap-order property (0-based array a)
| Property | Max-heap | Min-heap |
|---|---|---|
| Parent and child | parent children | parent children |
| Root | maximum | minimum |
| Example | [10, 5, 3, 4, 1] | [1, 3, 5, 4, 10] |
| Peek the root | ||
| Insert, delete root | ||
| Typical use | max priority queue, task scheduling by priority, heap sort | min priority queue, Dijkstra's algorithm, event simulation |
By hand
Checking two heaps
Max-heap [10, 5, 3, 4, 1]
- 1
Shape
Root 10; children 5 and 3; 4 and 1 under 5. The bottom level fills from the left: complete.
- 2
Node 10 (i = 0)
and . The root is the maximum.
- 3
Node 5 (i = 1)
and .
- 4
Node 3 (i = 2)
Its children would be at 5 and 6, past : a leaf, nothing to check. Valid max-heap after 4 comparisons.
Min-heap [1, 3, 5, 4, 10]
- 1
Node 1 (i = 0)
and . The root is the minimum.
- 2
Node 3 (i = 1)
and .
- 3
Node 5 (i = 2)
A leaf. Valid min-heap: same values as the max-heap, opposite arrangement.
Storage
A tree that lives in an array
Because the tree is complete, you can write its nodes level by level into a list and never leave a gap. The tree is never stored as nodes and pointers: the list is the heap, and parent-child links are pure arithmetic on the index.
Tree positions and array slots: [50, 40, 30, 10, 20, 25, 15]
[50, 40, 30, 10, 20, 25, 15], read straight off the levels: slot 0, then 1 and 2, then 3 to 6.Index arithmetic (0-based)
Every node of [50, 40, 30, 10, 20, 25, 15]
| i | Value | Parent (i - 1) // 2 | Left 2i + 1 | Right 2i + 2 |
|---|---|---|---|---|
| 0 | 50 | none (root) | 1: 40 | 2: 30 |
| 1 | 40 | 0: 50 | 3: 10 | 4: 20 |
| 2 | 30 | 0: 50 | 5: 25 | 6: 15 |
| 3 | 10 | 1: 40 | 7: none | 8: none |
| 4 | 20 | 1: 40 | 9: none | 10: none |
| 5 | 25 | 2: 30 | 11: none | 12: none |
| 6 | 15 | 2: 30 | 13: none | 14: none |
Deep dive
Why the index formulas work
Level holds slots and starts at index (0, 1, 3, 7, 15, ...), because the levels above it hold nodes. Take the node at position within level . Its children are positions and of level , since every node to its left contributes two children first.
Deriving left(i) = 2i + 1
def parent(i): return (i - 1) // 2def left(i): return 2 * i + 1def right(i): return 2 * i + 2heap = [50, 40, 30, 10, 20, 25, 15]n = len(heap)for i in range(n): kids = [heap[c] for c in (left(i), right(i)) if c < n] up = heap[parent(i)] if i else None print(f"i={i} value={heap[i]} parent={up} children={kids}")assert all(parent(left(i)) == i and parent(right(i)) == i for i in range(1000))Why it is fast
Height is floor(log2 n)
In a complete tree of height , levels to are full and the last level holds between and nodes. That pins between two powers of two, and so pins the height.
Height of a heap with n nodes
n.bit_length() - 1 gives the same value without floating-point rounding. See logarithms for why halving gives .| n | 1 | 3 | 7 | 8 | 15 | 16 | 1,000 | 1,000,000 |
|---|---|---|---|---|---|---|---|---|
| Height | 0 | 1 | 2 | 3 | 3 | 4 | 9 | 19 |
In code
Validating a heap
is_max_heap(a)
2i + 2 < n. For a min-heap, flip the comparisons.def is_heap(a, kind="max"): """True if list a satisfies the max-heap (or min-heap) order.""" ok = (lambda p, c: p >= c) if kind == "max" else (lambda p, c: p <= c) n = len(a) for i in range(n // 2): # parents only for c in (2 * i + 1, 2 * i + 2): if c < n and not ok(a[i], a[c]): return False return Trueprint(is_heap([10, 5, 3, 4, 1])) # Trueprint(is_heap([10, 5, 3, 4, 1], "min")) # False: 10 > 5print(is_heap([1, 3, 5, 4, 10], "min")) # Trueprint(is_heap([50, 30, 40, 10, 20, 35, 25])) # Trueprint(is_heap([50, 30, 40, 10, 45, 35, 25])) # False: 45 under 30What it buys
Operations that keep both rules
Every heap operation follows the same recipe: fix the shape first, then repair the order along one path. Insert appends to the next free slot and sifts the value up; extract moves the last value to the root and sifts it down. The full walkthroughs are in heap operations and heapify.
Shape first, order second
| Operation | Time | Why |
|---|---|---|
| Peek max (or min) | Always at heap[0] | |
| Insert (push) | Sift up at most the height | |
| Extract root (pop) | Sift down at most the height | |
| Build from n values | Most nodes are near the bottom; see heapify | |
| Search for any value | The order rule says nothing about left versus right | |
| Validate | One comparison per edge |
Compare
Heap vs binary search tree
Both are binary trees with an ordering rule, but the rules point in different directions. A binary search tree orders left against right (left < node < right), which makes search fast. A heap orders parent against child, which makes the extreme fast and nothing else.
| Binary heap | Binary search tree (balanced) | |
|---|---|---|
| Order rule | parent vs children | left < node < right |
| Shape | always complete | balanced only with rotations (AVL, red-black) |
| Storage | plain array, no pointers | nodes with left and right pointers |
| Find min or max | for one of them | for both |
| Search for x | ||
| Insert, delete | (delete root only) | (any key) |
| Sorted traversal | no (needs n pops) | yes, in-order in |
| Build from n values |
Heap or BST?
Choosing
Max-heap or min-heap?
Max-heap
Highest priority first, task scheduling, the k smallest values (evict the largest), heap sort in ascending order.
Min-heap
Lowest cost first: Dijkstra, event-driven simulation, merging k sorted lists, the k largest values (evict the smallest).
Two heaps
Running median: a max-heap for the lower half and a min-heap for the upper half.
Which heap for a top-k problem?
import heapqnums = [3, 10, 5, 1, 4]mn = nums[:]heapq.heapify(mn) # O(n), min-heap in placeprint(mn[0]) # 1, the minimummx = [-x for x in nums]heapq.heapify(mx) # min-heap of negatives = max-heapprint(-mx[0]) # 10, the maximumheapq.heappush(mx, -12)print(-heapq.heappop(mx)) # 12Recap
What to remember
- 1ShapeComplete binary tree, no holes
- 2OrderParent beats children on every edge
- 3Array2i + 1, 2i + 2, (i - 1) // 2
- 4RootMax or min in O(1)
Shape gives the array and the $\lfloor \log_2 n \rfloor$ height; order gives the root.
Key points
- A heap is a complete binary tree with the heap-order property: parent children (max-heap) or parent children (min-heap).
- The root holds the maximum (max-heap) or minimum (min-heap), so peek is .
- Stored level by level in an array: left , right , parent ; leaves start at .
- Height is , so insert and extract are ; building from a list is .
- A heap is not sorted and not a search structure: siblings are unordered and search is .
- Validate in by checking every parent-child edge; a gap-free array is complete automatically.
- Use a heap when you repeatedly need the extreme value; use a BST when you need search or sorted order.