Chapter 10
Heaps & Priority Queues
3 topics · 1 sections · beginner-friendly study notes · Updated
A binary heap is a complete binary tree stored in an array that keeps the min (or max) at the root; insert and extract are O(log n), peek is O(1), and building is O(n).
It implements priority queues, heap sort and Top-K selection.
Heaps underpin Dijkstra, Prim, scheduling and streaming problems; "build heap is O(n)" is a classic GATE proof.
OS task schedulers, event simulation, A* search, top trending items, median of data stream.
Binary Heap & Priority Queue
A binary heap is a complete binary tree with the heap property: in a min-heap each parent <= its children (root is the minimum); in a max-heap each parent >= children. A priority queue is an ADT (insert, extract-min/max, peek) commonly implemented with a heap.
In short: A tree where the boss is always the smallest (or largest), stored compactly in an array.
Think about it
GATE asks heap array layout, resulting arrays after operations, and complexities.
Array 0-indexed: parent (i-1)//2, left 2i+1, right 2i+2 (1-indexed: i//2, 2i, 2i+1).
Height = floor(log2 n).
Leaves occupy indices n//2 ..
n-1 so there are ceil(n/2) leaves.
Insert: append at the end, sift up while smaller than parent: O(log n).
Extract-min: swap root with last, remove last, sift down choosing the smaller child: O(log n).
Peek O(1).
Search arbitrary key O(n); delete arbitrary node O(log n) given its index; decrease-key O(log n) (sift up).
A heap is NOT sorted - only parent-child order holds; in a min-heap the maximum is somewhere among the leaves (n/2 candidates).
Compared to a sorted array (insert O(n)) and BST (O(log n) balanced, but more memory and pointer overhead) the heap is cache-friendly and simplest for min/max queries.
Fibonacci heap gives amortized O(1) insert/decrease-key (theoretical benefit for Dijkstra).
Python heapq is a min-heap only: for a max-heap push negated keys.
Ties and tuples: use (priority, counter, item) to avoid comparing uncomparable items.
Key points
- Heap property: Parent
<=children (min) or>=(max). - Sift-up / sift-down: Bubble a node toward the root / toward leaves to restore order.
- Priority queue: ADT serving the element of highest priority first.
- Operations: insert
O(log n), extractO(log n), peekO(1), buildO(n), searchO(n). - Max element of a min-heap is at a leaf: finding it takes
O(n).
Example
CodeMin-heap implementation:
class MinHeap:
def __init__(self): self.a = []
def push(self, x):
a = self.a; a.append(x); i = len(a) - 1
while i and a[(i - 1) // 2] > a[i]:
a[(i - 1) // 2], a[i] = a[i], a[(i - 1) // 2]
i = (i - 1) // 2
def pop(self):
a = self.a
a[0], a[-1] = a[-1], a[0]
top = a.pop()
self._down(0)
return top
def _down(self, i):
a, n = self.a, len(self.a)
while True:
s, l, r = i, 2 * i + 1, 2 * i + 2
if l < n and a[l] < a[s]: s = l
if r < n and a[r] < a[s]: s = r
if s == i: return
a[i], a[s] = a[s], a[i]; i = s
import heapq
h = []; heapq.heappush(h, 5); heapq.heappush(h, 1)
print(heapq.heappop(h)) # 1
max_heap = []; heapq.heappush(max_heap, -7) # max-heap via negationHeapify & Heap Sort
Heapify (build-heap) converts an arbitrary array into a heap by sifting down every internal node from index n//2 - 1 down to 0, in O(n) time. Heap sort builds a max-heap, then repeatedly swaps the root with the last element and sifts down on the shrinking heap: O(n log n), in place, not stable.
In short: Fix the heap from the bottom up, then repeatedly pull the biggest element to the end.
Think about it
The O(n) proof is a perennial GATE favourite; heap sort is the in-place O(n log n) worst-case sort.
Why build-heap is O(n) and not O(n log n): a node at height h costs O(h) to sift down and there are at most ceil(n / 2^(h+1)) nodes of height h, so total = sum over h of n/2^(h+1) * h = O(n * sum h/2^h) = O(n) (the series converges to 2).
Inserting n elements one by one is O(n log n).
Heap sort: build O(n), then n-1 extractions each O(log n): O(n log n) in best, average and worst case; space O(1); not stable; poor cache behaviour so quick sort is faster in practice, but heap sort has the worst-case guarantee (used inside introsort).
Ascending order uses a max-heap (largest goes to the end); descending uses a min-heap.
Number of comparisons for build-heap is at most 2n.
Heapifying [4,10,3,5,1]: sift 10 (index 1) -> children 5,1, ok; sift 4 at root swaps with 10: [10,5,3,4,1], then 4 vs children (index 3,4: none).
Partial heap sort (k extractions) finds the k largest in O(n + k log n).
Key points
Example
CodeBuild-heap and heap sort:
def sift_down(a, i, n): # max-heap
while True:
big, l, r = i, 2 * i + 1, 2 * i + 2
if l < n and a[l] > a[big]: big = l
if r < n and a[r] > a[big]: big = r
if big == i: return
a[i], a[big] = a[big], a[i]
i = big
def build_max_heap(a): # O(n)
for i in range(len(a) // 2 - 1, -1, -1):
sift_down(a, i, len(a))
def heap_sort(a): # O(n log n), O(1) space
n = len(a)
build_max_heap(a)
for end in range(n - 1, 0, -1):
a[0], a[end] = a[end], a[0]
sift_down(a, 0, end)Top K Elements Pattern
To find the K largest elements keep a MIN-heap of size K: for each element, push it; if size exceeds K pop the smallest. The heap ends with the K largest. Time O(n log k), space O(k). For K smallest use a max-heap.
In short: Keep a small leaderboard of K; the weakest member (heap top) is kicked out whenever a better one arrives.
Think about it
Top-K and merge-K are the most common heap interview patterns and test the choice of heap direction.
Using the opposite heap type is the key insight: the root of the min-heap is the K-th largest so far and the cheapest to compare/evict.
Alternatives: sort O(n log n); heapify all then pop k: O(n + k log n); quickselect O(n) expected.
Choose heap for streaming data or when k << n.
K-th largest = root of the size-K min-heap.
Top K frequent: count with a hash map (O(n)), then size-K min-heap on counts: O(n log k) (or bucket sort O(n)).
K closest points to origin: max-heap of size K on distance.
Merge K sorted lists: min-heap of (value, list index): O(N log K) where N is total elements.
Running median: max-heap for the lower half and min-heap for the upper half, rebalanced so sizes differ by at most 1: add O(log n), median O(1).
K-th smallest in a sorted matrix with heap: O((k + n) log n).
Task scheduling and Huffman coding also use extract-two-minimum loops.
Edge cases: k > n, k = 0, ties, negative numbers.
Key points
- Size-K heap: Fixed-capacity heap holding the best K seen so far.
- Two-heap median: Max-heap lower half + min-heap upper half.
- Quickselect: Average
O(n)selection of k-th element.
Example
CodeTop-K, merge K, running median:
import heapq
from collections import Counter
def k_largest(nums, k): # O(n log k)
h = []
for x in nums:
heapq.heappush(h, x)
if len(h) > k: heapq.heappop(h)
return sorted(h, reverse=True)
def top_k_frequent(nums, k):
cnt = Counter(nums)
return [x for x, _ in heapq.nlargest(k, cnt.items(), key=lambda p: p[1])]
def merge_k_lists(lists): # lists of sorted ints, O(N log K)
h = [(l[0], i, 0) for i, l in enumerate(lists) if l]
heapq.heapify(h); out = []
while h:
v, i, j = heapq.heappop(h); out.append(v)
if j + 1 < len(lists[i]):
heapq.heappush(h, (lists[i][j + 1], i, j + 1))
return out
class MedianFinder:
def __init__(self): self.lo, self.hi = [], [] # lo = max-heap (neg)
def add(self, x):
heapq.heappush(self.lo, -x)
heapq.heappush(self.hi, -heapq.heappop(self.lo))
if len(self.hi) > len(self.lo):
heapq.heappush(self.lo, -heapq.heappop(self.hi))
def median(self):
if len(self.lo) > len(self.hi): return -self.lo[0]
return (-self.lo[0] + self.hi[0]) / 2Solved examples
Insert 10, 4, 7, 2, 9 one by one into a min-heap. Give the array.
Array
Formula Applied:—Approach note: Parent of index i is (i-1)//2.
Build a max-heap from [3, 9, 2, 1, 4, 5] using bottom-up heapify.
Array
Formula Applied:—Approach note: Start at the last internal node.
Find the 3rd largest in a stream [5, 2, 8, 1, 9, 3] using a heap.
Heap state and answer
Formula Applied:—Approach note: Min-heap root is the K-th largest.
In a 1-indexed max-heap array [_, 20, 15, 10, 8, 12], what are the children indexes of the node at index 2?
Child indexes and values
Formula Applied:—Approach note: Parent of i is floor(i/2).
Real-world applications
Using Heaps & Priority Queues in real projects
OS task schedulers, event simulation, A* search, top trending items, median of data stream.
Common mistakes
❌ Myth: A heap is a sorted array.
Why this is wrong: Only parent-child order is enforced; siblings and levels are not ordered.
✅ Verified Truth: Heap gives O(1) min/max, not sorted traversal.
⚠️ Exam Tip: Array [1,5,2,6,7,3] is a valid min-heap but not sorted.
❌ Myth: Building a heap from n elements is O(n log n).
Why this is wrong: Most nodes are near the leaves and sift very short distances.
✅ Verified Truth: Bottom-up heapify is O(n); repeated insertion is O(n log n).
⚠️ Exam Tip: Quote sum of h/2^h converging to 2.
❌ Myth: Use a max-heap to find the K largest.
Why this is wrong: A max-heap of size K evicts the wrong element; you need to evict the smallest.
✅ Verified Truth: Use a min-heap of size K for K largest (max-heap for K smallest).
⚠️ Exam Tip: The heap root should be the candidate to discard.
Revision notes
A binary heap is a complete binary tree stored in an array that keeps the min (or max) at the root; insert and extract are O(log n), peek is O(1), and building is O(n). It implements priority queues, heap sort and Top-K selection.
High-Yield Quick Revision Points
- Min-heap: parent <= children; parent (i-1)//2, children 2i+1, 2i+2
- insert/extract O(log n), peek O(1), build O(n)
- Heap sort: max-heap, swap root to end, sift-down; O(n log n), in place, unstable
- Top K largest: min-heap size K, O(n log k); merge K lists O(N log K)
- Median: max-heap (low) + min-heap (high)
Practice questions
Time to build a heap from n elements bottom-up:
Index of the left child of node i (0-indexed array):
Where is the maximum in a min-heap?
Heap sort worst-case time and space:
Merging K sorted lists with N total elements using a heap: