Why does a Binary Heap store a complete binary tree inside a flat array with zero node pointers—and how does Floyd's bottom-up heapify construct an entire heap in O(N) linear time instead of O(N log N)?
In 30 Seconds
A Priority Queue is an abstract data type where every element enters with a priority and the highest-priority item is always extracted first [cite: 1.2.1, 1.2.2]. Under the hood, standard libraries implement it using a Binary Heap [a complete binary tree stored in a contiguous array where every parent is $\le$ its children (Min-Heap) or $\ge$ its children (Max-Heap)] [cite: 1.2.1, 1.2.2]. It delivers O(1) peek, O(log N) push/pop, and O(N) batch construction [cite: 1.2.1, 1.2.2].
The Real-World Analogy: Hospital Emergency Room Triage
In a standard FIFO Queue, patients are treated strictly by arrival timestamp. In an Emergency Room Priority Queue, every patient gets an urgency score (`1 = Critical`, `5 = Minor`): whenever a doctor opens up, the patient with urgency `1` at the root goes in immediately—even if they arrived 10 seconds ago!
The Mathematical Invariants (Shape + Heap Order + O(N) Build Proof)
- Complete Tree Shape Invariant: Every level is completely filled except possibly the bottom level, which fills strictly left-to-right [cite: 1.2.2, 1.2.3]. This guarantees exact index arithmetic:
parent = (i - 1) // 2,left = 2*i + 1,right = 2*i + 2[cite: 1.2.2]. - Why Bottom-Up
heapifyRuns in O(N) (Not O(N log N)): Half of all nodes in a binary tree ($N/2$) are leaves at height `0` (requiring `0` swaps!), $N/4$ nodes sit at height `1` ($\le 1$ swap), $N/8$ at height `2` ($\le 2$ swaps). Summing $\sum_{h=0}^{\log N} \frac{N}{2^{h+1}} \cdot h = O(N)$!
Under the Hood: CPU Cache Locality, D-ary Heaps & Lazy Deletion
- Zero Pointer Overhead + L1 Cache Hits: Storing a heap in a flat array saves 16 bytes of
left/rightpointers per node and keeps parent/child indices close in contiguous RAM—avoiding pointer-chasing cache misses [cite: 1.2.2, 1.2.3]. - 4-ary Heaps in Production Routers: High-performance engines (like Linux timers and Dijkstra routers) often use 4-ary heaps (4 children per node) because all 4 children fit inside a single 64-byte L1 cache line, cutting tree height in half ($\log_4 N$)!
- Lazy Deletion Pattern (The Red-Coder Trick): Standard heaps do not support $O(\log N)$ arbitrary element removal by value. Instead, store a hash map or
deletedset and discard stale entries lazily only when they float up toheap[0]duringpop()!
Show Me The Code
# Day 23: Complete Min-Heap with O(N) Bottom-Up Build & Lazy Deletion in Python
class MinHeap:
def __init__(self, items=None):
self.data = list(items) if items else []
if self.data:
# Floyd's O(N) bottom-up build starting from last non-leaf node
for i in range((len(self.data) // 2) - 1, -1, -1):
self._sift_down(i)
def peek(self):
return self.data[0] if self.data else None
def push(self, val):
self.data.append(val)
self._sift_up(len(self.data) - 1)
def pop(self):
if not self.data:
return None
if len(self.data) == 1:
return self.data.pop()
top = self.data[0]
self.data[0] = self.data.pop()
self._sift_down(0)
return top
def _sift_up(self, idx):
while idx > 0:
parent = (idx - 1) // 2
if self.data[idx] < self.data[parent]:
self.data[idx], self.data[parent] = self.data[parent], self.data[idx]
idx = parent
else:
break
def _sift_down(self, idx):
n = len(self.data)
while True:
smallest = idx
left = 2 * idx + 1
right = 2 * idx + 2
if left < n and self.data[left] < self.data[smallest]:
smallest = left
if right < n and self.data[right] < self.data[smallest]:
smallest = right
if smallest != idx:
self.data[idx], self.data[smallest] = self.data[smallest], self.data[idx]
idx = smallest
else:
break
Speed & Memory
| Operation | Time Complexity | Space Complexity | Why? |
|---|---|---|---|
peek() | O(1) | O(1) | Global min/max always sits at data[0] [cite: 1.2.1, 1.2.2]. |
push() / pop() | O(log N) | O(1) | Sifts along one root-to-leaf path of length $\lfloor \log_2 N \rfloor$ [cite: 1.2.1, 1.2.2]. |
heapify(arr) | O(N) | O(1) in-place | Floyd's bottom-up sift-down converges linearly [cite: 1.2.2]. |
Traps To Avoid
- Trap 1: Thinking a Binary Heap is sorted across levels (e.g., expecting
heap[1] < heap[2]). Fix: A heap only guaranteesparent <= children—siblings have no ordering relationship [cite: 1.2.3]! - Trap 2: Pushing custom objects or tuples with duplicate priorities into Python's
heapq(e.g.,(priority, node)). Fix: If two priorities tie, Python compares the second tuple element (`node`), crashing if `node` lacks `<`—always insert a tie-breaker counter: `(priority, tie_id, node)`!
Practice
- Easy: Find the K-th largest element in a stream of numbers using a fixed-size Min-Heap of size $K$.
- Medium: Merge $K$ sorted linked lists in O(N log K) total time using a Min-Heap.
- Hard: Find the Sliding Window Median over an array of length $N$ in O(N log K) time using Two Heaps + Lazy Deletion!
TL;DR
- A Binary Heap powers Priority Queues using a flat contiguous array (
left = 2i + 1,right = 2i + 2) for cache efficiency [cite: 1.2.1, 1.2.2]. peekis O(1),push/popare O(log N), and Floyd's bottom-upheapifybuilds a heap in O(N) [cite: 1.2.1, 1.2.2].
References consulted: GeeksforGeeks Priority Queue Guide & Princeton Algorithms Heap Notes — referenced for verification — all content above is original.
Covered Log Update
Already covered: [Big-O notation, Arrays, Two Pointers, Strings, Sliding Window, Prefix Sums, Recursion basics, Singly Linked List, Doubly Linked List, Stack, Queue, Deque, Fast & Slow pointers, Binary Search, Bubble/Selection/Insertion Sort, Merge Sort, Quick Sort, Counting & Bucket Sort, Hashing & Hash Maps, Binary Tree, Tree Traversals (DFS/BFS), Binary Search Tree, Heap & Priority Queue]