Min and max heap
- Algorithms course
- Intermediate
- Lesson 37/80
- 4 min
Difference between min-heap and max-heap.
Min and max heap
In a min-heap each node is smaller than or equal to its children; the root is the smallest. In a max-heap each node is larger than or equal to its children; the root is the largest.
A heap is stored as a complete binary tree in an array. Parent (i-1)//2, left child 2i+1, right child 2i+2.
Min-heap is used to get the smallest element quickly in a priority queue; max-heap for the largest.
Parent-child
In the array representation, the parent of node at index i is (i-1)//2, left child 2i+1, right child 2i+2.
The root is arr[0] and has no parent. Leaves are in the second half of the array (i ≥ n//2).
These formulas give parent-child relations in O(1); no pointers needed.
Practice Check min-heap
Write is_min_heap(arr). Each child must be >= parent. Print True with print(is_min_heap([1, 3, 2, 5, 4])).
Starter code
def is_min_heap(arr):
# Check min-heapSample solution
def is_min_heap(arr):
# Check min-heap
for i in range(1, len(arr)):
if arr[(i - 1) // 2] > arr[i]:
return False
return True
print(is_min_heap([1, 3, 2, 5, 4]))Expected output
True
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What is the root in a min-heap?
- The largest
- The smallest element Correct answer
- The median
- Random
Explanation: The smallest element
2 Parent
parent = (i - 1) // ____
parent = (i - 1) // 2
Explanation: 2 is right.
3 Min and max heap: match the terms
| Term | Meaning |
|---|---|
Min-heap |
Root smallest |
Max-heap |
Root largest |
Parent |
(i-1)//2 |
Left child |
2i+1 |