Data Structures · Visualization
Max-Heap: Introduction
Max Heap
A max-heap is a complete binary tree (filled level by level, left to right, with no gaps) where every parent's value is greater than or equal to both of its children's values. Time: O(1) to peek the max, O(log n) to insert or remove the max. Space: O(n).
Big-O: Insert/extract O(log n); build O(n).
Max-Heap: Introduction
Max HeapA max-heap is a complete binary tree (filled level by level, left to right, with no gaps) where every parent's value is greater than or equal to both of its children's values. This means the single largest value in the entire structure is always sitting right at the root, ready to be accessed instantly. Max-heaps are almost always stored in a plain array rather than with node pointers, since the complete-tree shape lets you calculate any node's parent/children using simple index math.
How Max-Heap: Introduction Works
- Store elements in an array where index 0 is the root.
- For any node at index i, its children live at indices 2i+1 and 2i+2, and its parent lives at index (i-1)/2.
- Maintain the rule that every node's value is >= both of its children's values.
- Use this shape to always find the maximum instantly at index 0.
Max-Heap: Introduction Worked Example
Input: A valid max-heap stored as an array
- Array: [50, 30, 40, 10, 20]
- Root (index 0) = 50, its children are index 1 (30) and index 2 (40) — 50 >= both
- Node 30 (index 1) has child index 3 (10) — 30 >= 10
Output: 50 / \ 30 40 / \ 10 20
Press ▶ Run to watch it step by step.
# Max-heap inside a plain list
# children of i: 2i+1, 2i+2; parent: (i-1)//2
heap = [50, 30, 40, 10, 20]
# root heap[0] is always the maximum
print(heap[0])
# example: intro on [50, 30, 40, 10, 20]Max-Heap: Introduction Time & Space Complexity
When to Use Max-Heap: Introduction
- Implementing priority queues where the highest-priority item is served first
- Heap sort (repeatedly extracting the max to build a sorted array)
- Finding the k largest elements efficiently
- Task schedulers that always run the most urgent job next
Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Ready for the next step?
See the same ideas in action — visualize the algorithms that operate on these structures, or take a guided course.