Binary Heaps — Min-Heap and Max-Heap Structure — Complete Beginner Guide
Learning Objectives
- Define complete binary tree shape
- Map tree nodes to array indices
- Explain min-heap and max-heap order rules
- Implement insert with sift up
- Implement extract with sift down
What Is a Binary Heap?
A binary heap is a complete binary tree stored in an array. Every level is filled except possibly the last, which fills from left to right.
A heap also keeps an order rule between parents and children. That rule is separate from the shape rule.
| Rule Family | Requirement |
|---|---|
| Shape | Complete binary tree, filled left to right |
| Min-heap order | Parent key less than or equal to children |
| Max-heap order | Parent key greater than or equal to children |
Heaps do not keep full sorted order. They only guarantee the extreme value sits at the root.
Array Mapping
Because the tree is complete, array slots mirror breadth-first placement.
| Relation | Index Formula for Zero-Based Array |
|---|---|
| Root | index zero |
| Parent of i | i minus one, then integer divide by two |
| Left child of i | two times i, plus one |
| Right child of i | two times i, plus two |
def parent(i):
return (i - 1) // 2
def left_child(i):
return 2 * i + 1
def right_child(i):
return 2 * i + 2
heap = [3, 5, 6, 8, 9, 12]
print(parent(4), left_child(1), right_child(1))
Insert and Sift Up
Append the value at the end, then bubble it upward while the heap order breaks.
def sift_up(heap, index):
while index > 0:
p = parent(index)
if heap[index] >= heap[p]:
break
heap[index], heap[p] = heap[p], heap[index]
index = p
def push(heap, value):
heap.append(value)
sift_up(heap, len(heap) - 1)
min_heap = []
for value in [7, 2, 5, 1, 9]:
push(min_heap, value)
print(min_heap)
Insert runs in O(log n) because the path from leaf to root has height about log n.
Extract and Sift Down
Remove the root extreme, move the last element into the root slot, then sink it until order restores.
def sift_down(heap, index):
n = len(heap)
while True:
smallest = index
left = left_child(index)
right = right_child(index)
if left < n and heap[left] < heap[smallest]:
smallest = left
if right < n and heap[right] < heap[smallest]:
smallest = right
if smallest == index:
break
heap[index], heap[smallest] = heap[smallest], heap[index]
index = smallest
def pop_min(heap):
if not heap:
raise IndexError("empty heap")
last = heap.pop()
if heap:
heap[0] = last
sift_down(heap, 0)
def pop_min_value(heap):
value = heap[0]
pop_min(heap)
return value
print(pop_min_value(min_heap))
For a max-heap, flip every comparison so parents stay larger than children.
Heapify: Build in Linear Time
You can build a heap from an unordered array by sifting down every internal node from the last parent back to the root. This runs in O(n), which beats n separate inserts.
def heapify(heap):
n = len(heap)
start = n // 2 - 1
for i in range(start, -1, -1):
sift_down(heap, i)
data = [9, 4, 7, 1, 3, 6]
heapify(data)
print(data)
Complexity Table
| Operation | Time | Notes |
|---|---|---|
| Find min or max | O(1) | Root only |
| Insert | O(log n) | Sift up path |
| Extract min or max | O(log n) | Sift down path |
| Heapify build | O(n) | Bottom-up sifts |
| Search arbitrary key | O(n) | No search path |
| Space | O(n) | Compact array |
Heap versus Sorted Array
A sorted array finds the minimum at O(1) but inserts at O(n). A heap finds the minimum at O(1) and inserts at O(log n). That trade makes heaps perfect for ongoing streams.
Heap Visualization Drill
Draw heaps as both trees and arrays side by side. Mark each parent index and underline its two children. When you sift up after an insert, circle the violated parent-child pair, swap, and redraw only that path. When you sift down after an extract, compare both children before choosing the swap target.
| Array Slot | Value | Left Child Slot | Right Child Slot |
|---|---|---|---|
| 0 | 2 | 1 | 2 |
| 1 | 5 | 3 | 4 |
| 2 | 3 | 5 | 6 |
def children(i):
return 2 * i + 1, 2 * i + 2
print(children(0)) # 1, 2
print(children(1)) # 3, 4
A common bug is swapping with only one child and breaking order with the other. Always evaluate left and right, then pick the correct partner. Another bug is forgetting that the array beyond the live length is not part of the heap during extract operations.
Key Takeaways
💡
- Heaps need a complete shape plus a parent-child order rule
- Array index math replaces pointer chasing
- Insert sifts up; extract sifts down; both cost O(log n)
- Heapify builds a heap from raw data in O(n)
- Heaps track extremes fast but do not support fast full search
Practice Questions
- Map the array 4, 8, 6, 10, 9, 7 to tree positions using the child formulas.
- Walk through inserting 1 into the min-heap 2, 5, 3, 8 and describe each swap.
- Why is heapify O(n) instead of O(n log n) when built from an unordered list?
Extended Learning: Beyond the Basics
Key Concepts Summary
This lesson covers fundamental concepts that serve as building blocks for more advanced topics. Master these basics before moving to intermediate and advanced material.
Prerequisite Knowledge
Before studying this topic in depth, ensure you understand:
- Basic definitions and terminology
- Core formulas and their derivations
- Common applications in real-world scenarios
- Typical pitfalls and misconceptions
Step-by-Step Walkthrough
Let us work through a complete example to solidify understanding:
Step 1: Identify the problem type. Determine which category this problem falls into and which approach is most appropriate.
Step 2: Apply the relevant formula. Substitute known values into the appropriate equation, paying attention to units and constraints.
Step 3: Simplify and solve. Work through the algebra step by step, checking each intermediate result.
Step 4: Verify the answer. Check that the solution satisfies the original conditions and makes logical sense.
Common Mistakes to Avoid
- Misidentifying the problem type — Always start by categorizing the problem
- Incorrect formula application — Verify the formula applies to your specific case
- Unit errors — Always check units are consistent throughout
- Sign errors — Pay careful attention to positive and negative values
- Rounding too early — Keep full precision until the final answer
- Forgetting constraints — Check that solutions satisfy all given conditions
Real-World Applications
Understanding this concept is essential for:
- Advanced problem solving in examinations
- Building intuition for more complex topics
- Developing analytical thinking skills
- Applying mathematical reasoning to practical situations
Practice Exercises
- Basic: Solve 5 problems of increasing difficulty using the core concept.
- Intermediate: Apply the concept to word problems with multiple steps.
- Advanced: Combine this concept with 2-3 other topics in a comprehensive problem.
- Challenge: Create your own problem that requires this concept plus additional knowledge.
Interview and Exam Tips
- Common question patterns: Identify which exam or interview formats test this topic
- Time management: Practice completing problems within time constraints
- Common traps: Know the typical mistakes examiners set as distractors
- Verification strategy: Develop a quick method to check your answer
Related Topics
- Previous Topic — Build on the foundation laid here
- Next Topic — See how this concept extends to more advanced material
- Practice Problems — Additional exercises with solutions
- Video Explanation — Visual walkthrough of key concepts
Quick Reference Card
| Concept | Formula/Rule | Key Insight | Common Use |
|---|---|---|---|
| Core Definition | See main text | Understand the intuition | Foundation for all applications |
| Key Formula | See main text | Memorize the derivation | Direct problem solving |
| Special Case | See main text | Recognize when it applies | Simplifies complex problems |
| Edge Case | See main text | Know the limitations | Avoids errors |
Further Reading
For students who want to go deeper:
- Standard textbooks on the subject
- Research papers applying this concept
- Online courses with video explanations
- Practice problem collections with detailed solutions