Heaps
The notes
Definition
A complete binary tree that satisfies the heap property.
Complete tree
- Filled level by level, left to right (no gaps except on the last level)
- A tree with a gap before the last node is NOT a complete tree
Two types
Max heap
- Root is the largest element
- Parent is always >= its children
- Value decreases down
Min heap
- Root is the smallest element
- Parent is always <= its children
- Value increases down
How a heap is stored (array representation)
Index formulas
- Left child(i) = 2i + 1
- Right child(i) = 2i + 2
- Parent(i) = (i - 1) / 2
Key operations
Insertion (push)
- 1. Add the new element to the next available spot
- 2. "Bubble up" (percolate up) to fix the property (swap with parent if needed)
Extraction (pop)
- 1. Remove the root (max/min)
- 2. Replace the root with the last element
- 3. "Sink down" (percolate down) to fix the property (swap with child if needed)
Why heaps are useful
- Priority queues: a line of tasks with priorities
- Heapsort: efficient sorting
- Top K elements: finding the largest or smallest numbers
Time complexity
- O(log N) for insert/delete
- O(1) for peek
Data structures deck
Make them stick
Sign in to see every card full size, tick the ones you've got, come back to the rest later, and keep your own notes on each card.









