Always the Max (or Min) at the Top
A binary heap is a complete binary tree where every parent is ≥ (max-heap) or ≤ (min-heap) its children. This property makes the root the maximum or minimum element, retrievable in O(1) time.
Insert (push)
Add to end, bubble up — O(log N)
Extract (pop)
Remove root, sift down — O(log N)
Max-Heap in Action
Watch a real insert and extract-max sequence — every comparison and swap shown, one step at a time.
Starting max-heap — every parent is already ≥ its children.
The Dense Array Structure
Because a heap is a complete binary tree (filled layer-by-layer from left to right), it can be perfectly packed into a flat array without storing child or parent pointers. This layout has superior CPU cache locality because nodes are contiguous in memory.
Parent(i)
Math.floor((i - 1) / 2)Left(i) & Right(i)
Left = 2*i + 1 | Right = 2*i + 2[50, 30, 40, 10, 20, 35] is a completely valid max-heap — only the root is guaranteed to be the extreme value. Reading left-to-right gives no ordering guarantee beyond "each parent ≥ its two children."The O(N) Heapify Secret
A naive way to build a heap of size N is to start with an empty heap and insert elements one by one. Each insertion takes O(log N), leading to a total time of O(N log N).
However, we can build a heap in O(N) time by using bottom-up heap construction (sifting down from the bottom non-leaf nodes up to the root).
Why is it O(N)?
The next layer up contains N/4 nodes, which need at most 1 sift-down step. The layer above that has N/8 nodes, requiring at most 2 steps, and so on.
Mathematically, the total sifting work converges:
Essential Heap Strategies
1. Bottom-Up Heapify (Sift Down)
How it Works
- Start from index
n/2 - 1(last non-leaf node). - Sift down each node to its correct position relative to children.
- Allows constructing a valid heap in linear
O(N)time. - Enables efficient in-place heapsort without extra space.
2. Top-K Largest Elements
How it Works
- Initialize a min-heap.
- Push each element into the heap one-by-one.
- If heap size exceeds
K, evict the smallest element (root). - Takes
O(N log K)time and uses onlyO(K)memory.
3. Dynamic Median Tracking (Two Heaps)
How it Works
- Divide numbers: left lower half in a Max-Heap, right higher half in a Min-Heap.
- Add number to Max-Heap, then transfer Max-Heap's root to Min-Heap to balance values.
- If size of Max-Heap is smaller, pull from Min-Heap back to balance sizes.
- Get median in
O(1)time, add elements inO(log N).
When to Use What
Use a Heap
- Repeatedly need max/min values
- Finding K-th largest / smallest
- Dynamic median tracking
- Merging K sorted streams
Skip the Heap
- Need fully sorted array (use Sort)
- Single pass of max/min (use simple scan)
- Values bounded (use bucket/counting sort)
Real-world Heap Systems
1. Dijkstra's Shortest Path Algorithm
Problem: Find the shortest path from a starting node to all other nodes in a weighted graph.
Core Logic: We use a min-heap to keep track of active paths. At each step, we extract the node with the absolute minimum accumulated distance from the heap, which is guaranteed to be finalized, then relax its neighbors.
2. Merge K Sorted Lists
Problem: Merge K sorted linked lists into one single sorted list.
Core Logic: Push the head node of each of the K lists into a min-heap. Pop the minimum node, append it to the result list, and push that node's next node back into the heap. This ensures linear-like merge overhead of O(N log K) instead of quadratic comparisons.
3. CPU Load Balancers & Task Schedulers
Problem: Dispatch tasks based on priority or dynamic response load.
Core Logic: CPU tasks are added to a priority queue (implemented as a binary heap). The scheduler pulls the highest priority task (min-heap based on deadline or priority score) to process next, ensuring key system operations are never blocked.
How to Spot a Heap Problem
Heaps show up whenever a problem keeps asking for the current extreme (max or min) while the underlying data keeps changing. Watch for phrasing like:
Classic problems: Kth Largest Element in an Array, Top K Frequent Elements, K Closest Points to Origin, Merge K Sorted Lists, Find Median from Data Stream, Task Scheduler.
Mistakes That Cost Interviews
1. Treating a heap as a sorted array
Only the root is guaranteed to be the extreme value — the rest of the array is not in order. Don't index into the middle expecting sorted output.
2. Assuming JavaScript has a built-in heap
Python has heapq, Java/C++/Go have PriorityQueue / priority_queue / container/heap — JavaScript has none built in. You must bring or hand-roll a Min/MaxHeap class.
3. Flipping the comparator by accident
Python's heapq is always a min-heap — negate values to fake a max-heap. Mixing this up silently returns the smallest element instead of the largest.
4. Wrong heap size for "top K"
Keep a min-heap of size K and evict the smallest once it grows past K — not a max-heap of all N elements, which uses O(N) space and still needs K pops at the end.
Ready to Practice?
"A heap is a priority queue — not a sorted list."