DSA Notes
Master the min-heap data structure with complete from-scratch implementation — insert with sift-up, extract minimum with sift-down, decrease key, delete arbitrary element, build heap in O(n), and heap sort. All operations with detailed traces and complexity analysis.
The Min-Heap Property
In a min-heap, every parent node is ≤ its children. The minimum element is always at the root (index 0).
Array: [1, 3, 2, 9, 7, 4, 8]
Operation Traces
Insert (Sift-Up)
| Append 2 to end | [1, 3, 4, 9, 7, 6, 8, 2] |
| i=7: parent=3, data[3]=9 > data[7]=2 | SWAP |
| i=3: parent=1, data[1]=3 > data[3]=2 | SWAP |
| i=1: parent=0, data[0]=1 ≤ data[1]=2 | STOP |
| Final | [1, 2, 4, 3, 7, 6, 8, 9] ✓ |
Extract Minimum (Sift-Down)
| Save root | min_val = 1 |
| Move last to root | [8, 3, 2, 9, 7, 4] |
| i=0 (value=8) | left=1(3), right=2(2) |
| smallest = 2 (right child, value=2) | SWAP |
| i=2 (value=8) | left=5(4), right=6(none) |
| smallest = 5 (left child, value=4) | SWAP |
| i=5 (value=8): left=11(none) | STOP |
| Final | [2, 3, 4, 9, 7, 8] ✓, return 1 |
Build Heap in O(n) — Why Not O(n log n)?
# Naive approach: insert n elements one by one
# Each insert: O(log n) → Total: O(n log n)
# Heapify (build_heap): O(n)
def build_heap_efficient(arr):
n = len(arr)
for i in range(n // 2 - 1, -1, -1):
sift_down(arr, n, i)Why O(n)? The mathematical analysis:
At height h from bottom:
- Nodes at height h: at most ⌈n/2^(h+1)⌉
- Work per node at height h: O(h) for sift-down
Total work = Σ h × n/2^(h+1) from h=0 to log n = n × Σ h/2^(h+1) = n × 1 (geometric series converges to 1) = O(n)
Heap Sort Using Min-Heap
Merge K Sorted Arrays Using Min-Heap
Operations Complexity
| Operation | Time | Notes |
|---|---|---|
push(value) | O(log n) | Sift up from leaf |
pop() | O(log n) | Sift down from root |
peek() | O(1) | Direct root access |
decrease_key(i, v) | O(log n) | Sift up from index i |
delete(i) | O(log n) | decrease_key + pop |
build_heap(arr) | O(n) | Bottom-up heapify |
Summary
Min-heap: parent ≤ children, minimum always at root.
- Insert: Append to end, sift up — O(log n)
- Extract min: Swap root with last, sift down — O(log n)
- Build from array: Bottom-up heapify — O(n)
- All sift operations: O(log n) = O(tree height) = O(log n) for complete binary tree
- Python's
heapq: Already implements min-heap — use it in practice
*Next Lesson: Max Heap*
Exam Focus
Revise definitions, diagrams, examples, and short-answer points for Min Heap — Complete Implementation with All Operations.
Interview Use
Prepare one clear explanation, one practical example, and one common mistake for this Data Structures & Algorithms topic.
Search Terms
data-structures-algorithms, data structures & algorithms, data, structures, algorithms, heaps, min, heap
Related Data Structures & Algorithms Topics