Priority-based operations - Min Heap, Max Heap, Heap Sort, Heapify
Data Structure Module — Maintaining order dynamically
| # | Topic | Why It Matters |
|---|---|---|
| 1 | Heap Definition | Complete binary tree + Heap property |
| 2 | Height of Heap | ⌊log₂ n⌋ — the secret to O(log n) operations |
| 3 | Heapify | Restoring order in O(log n) time |
| 4 | Build Heap | The famous O(n) exam trap |
| 5 | Heap Sort | Reliable, in-place, O(n log n) sorting |
A heap is NOT just any binary tree. It must satisfy two strict rules:
A heap must be a Complete Binary Tree. This means the tree is filled level by level, from left to right. The last level may be incomplete, but it must be filled starting from the leftmost position.
Max Heap: Min Heap:
[90] [10]
/ \ / \
[70] [50] [30] [20]
/ \ / / \ /
[30] [10][40] [70] [50][40]
Parent ≥ Children Parent ≤ Children
Crucial insight: A heap is partially ordered, not fully sorted! Siblings have NO guaranteed relationship. You only know the parent is ≥ or ≤ the children.
Why are heap operations so fast? It's all about the height of the tree.
Height of a heap = ⌊log₂ n⌋
Because a heap is a complete binary tree, it is always perfectly balanced.
Any operation that travels from the root to a leaf takes O(log n) time. The structure naturally bounds the worst-case performance!
Heapify is the process of restoring the heap property when a single node violates it.
Imagine a max-heap where the root is suddenly replaced by a very small number. To fix the heap, that small number must "float down" (swap with its largest child) until it reaches a valid position.
Heapify Down (Max-Heap example):
The root [10] violates the property.
[10] ← violation!
/ \
[70] [50]
/ \
[30] [20]
Step 1: Swap 10 with the larger child (70)
[70]
/ \
[10] [50]
/ \
[30] [20]
Step 2: 10 still violates property. Swap with larger child (30)
[70]
/ \
[30] [50]
/ \
[10] [20] ← Heap restored!
Because heapify is O(log n):
How do we take an unsorted array and turn it into a valid heap?
We call heapify() on all non-leaf nodes, starting from the last non-leaf node up to the root.
If heapify takes O(log n), and we call it n/2 times, the complexity must be O(n log n), right?
WRONG.
Build Heap from Array = O(n)
Why? Most of the nodes in a complete binary tree are at the bottom (leaves).
When you sum the mathematical series: sum(h × nodes at height h), it tightly converges to O(n).
Exam Gold: Never say building a heap is O(n log n). It is strictly O(n).
Heap Sort leverages the max-heap to sort an array in place.
Step-by-step logic:
Array: [30, 10, 50, 20, 40]
1. Build Max Heap: [50, 40, 30, 20, 10]
2. Swap 50 (root) with 10 (last): [10, 40, 30, 20 | 50(sorted)]
3. Heapify root (10): [40, 20, 30, 10 | 50(sorted)]
4. Swap 40 with 10: [10, 20, 30 | 40, 50(sorted)]
5. Heapify root (10): [30, 20, 10 | 40, 50(sorted)]
... and so on.
| Metric | Value | Reason |
|---|---|---|
| Time Complexity | O(n log n) | O(n) to build + n × O(log n) extractions |
| Space Complexity | O(1) | Sorts entirely in-place! |
| Stable? | No | Equal elements can jump around during heapify. |
Heap sort is disciplined and reliable. It never degrades to O(n²) like Quick Sort can. However, it is often slower than Quick Sort in practice due to poor cache locality (jumping around array indices).
Heaps are beautifully mapped to arrays without needing node objects or pointers.
For any element at index i (using 0-based indexing):
# Python uses heapq (Min-Heap by default)
import heapq
# Start with unsorted list
arr = [30, 10, 50, 20, 40]
# Convert to heap IN-PLACE - O(n)
heapq.heapify(arr)
print(arr) # [10, 20, 50, 30, 40] -> Root is 10
# Push - O(log n)
heapq.heappush(arr, 5)
# Pop min - O(log n)
smallest = heapq.heappop(arr)
| Metric / Concept | Details |
|---|---|
| Height | ⌊log₂ n⌋ |
| Heapify | O(log n) |
| Build Heap | O(n) (Exam favourite!) |
| Heap Sort | O(n log n), O(1) space, NOT stable |
| Min-Heap Root | Always the smallest element |
| Max-Heap Root | Always the largest element |
One-liner for each concept:
| Concept | Key Takeaway |
|---|---|
| Heap Structure | Complete binary tree. Filled left to right, level by level. |
| Heap Property | Max-heap = Parent ≥ Children. Min-heap = Parent ≤ Children. |
| Height | log n. This keeps all traversal bounds tight to O(log n). |
| Build Heap | Converts unsorted array to heap. Takes O(n) time. |
| Heapify | Bubbles a node down to restore property. Takes O(log n) time. |
| Heap Sort | In-place! O(n log n) time, O(1) space. Unstable. |
| Array Maths | Parent: (i-1)/2, Left: 2i+1, Right: 2i+2. |
The Golden Rules:
-1 before pushing, and multiply by -1 when popping.Video Courses:
Practice Problems:
Test your understanding with step-by-step solutions
10 questions · 90s per question
Each question has a 90-second time limit. Unanswered questions will be auto-submitted when time runs out.