Heaps and Priority Queues (DSA #11)
You need the largest of a million items right now, and you will need the next largest right after, and the next, while new items keep arriving. Sorting once is \(O(n \log n)\) and then stale; a sorted list costs \(O(n)\) per insert. A heap gives you the extreme element in \(O(1)\), and extraction or insertion in \(O(\log n)\), no matter the incoming order. It is the data structure behind priority queues, schedulers, Dijkstra, and every “top k” question.
This chapter builds the binary heap from scratch, derives the array representation, and covers the patterns: top-k, k-way merge, and the two-heaps trick for running medians.
The priority queue abstraction
A priority queue keeps items with priorities and always removes the highest (or lowest) priority first. It is not FIFO or LIFO; it is “most important”. The binary heap is the standard efficient implementation.
Operations:
| Operation | Binary heap |
|---|---|
| peek min/max | \(O(1)\) |
| push | \(O(\log n)\) |
| pop min/max | \(O(\log n)\) |
| build from \(n\) items | \(O(n)\) |
| search arbitrary value | \(O(n)\) |
The binary heap: shape + order
A binary heap is a complete binary tree (every level full except the last, filled left to right) satisfying the heap property:
- Min-heap: every parent \(\le\) its children, so the minimum is at the root.
- Max-heap: every parent \(\ge\) its children, so the maximum is at the root.
Because the tree is complete, it packs perfectly into an array:
\[ \text{left}(i) = 2i + 1, \quad \text{right}(i) = 2i + 2, \quad \text{parent}(i) = \lfloor (i-1)/2 \rfloor \]
No pointers, no wasted slots. The root is index 0.
\begin{tikzpicture}[font=\rmfamily, >=stealth,
n/.style={draw, thick, circle, minimum size=0.62cm, font=\small\bfseries, inner sep=0pt},
a/.style={->, thick}]
\node[n, fill=orange!28] (r) at (0,0) {2};
\node[n, fill=blue!12] (l) at (-1.1,-0.9) {5}; \node[n, fill=blue!12] (rr) at (1.1,-0.9) {4};
\node[n, fill=green!16] (ll) at (-1.8,-1.8) {7}; \node[n, fill=green!16] (lr) at (-0.5,-1.8) {9};
\node[n, fill=green!16] (rl) at (0.6,-1.8) {8};
\draw[a] (r) -- (l); \draw[a] (r) -- (rr);
\draw[a] (l) -- (ll); \draw[a] (l) -- (lr); \draw[a] (rr) -- (rl);
\node[font=\rmfamily\small, text=black!60, anchor=north] at (0,-2.4) {tree};
\foreach \v [count=\i from 0] in {2,5,4,7,9,8} { \node[draw, thick, minimum size=0.5cm, font=\small\bfseries, fill=blue!8] at (3.2+\i*0.6,-0.9) {\v}; }
\node[font=\rmfamily\small, text=black!60, anchor=north] at (4.5,-1.5) {array};
\end{tikzpicture}
Insert: sift up
Add the item at the end (keeping the tree complete), then bubble it up while it violates the heap property:
def push(heap, x):
heap.append(x)
i = len(heap) - 1
while i > 0:
parent = (i - 1) // 2
if heap[parent] <= heap[i]: # min-heap satisfied
break
heap[parent], heap[i] = heap[i], heap[parent]
i = parent
Each swap moves the item one level toward the root, so it is \(O(\log n)\).
Pop: sift down
Move the last item to the root (removing the root), then bubble it down, swapping with the smaller child:
def pop(heap):
root = heap[0]
last = heap.pop()
if heap:
heap[0] = last
i, n = 0, len(heap)
while True:
l, r, smallest = 2*i+1, 2*i+2, i
if l < n and heap[l] < heap[smallest]: smallest = l
if r < n and heap[r] < heap[smallest]: smallest = r
if smallest == i: break
heap[i], heap[smallest] = heap[smallest], heap[i]
i = smallest
return root
Choosing the smaller child to swap is essential for a min-heap; swapping with the larger child can violate the property deeper down.
\begin{tikzpicture}[font=\rmfamily, >=stealth,
n/.style={draw, thick, circle, minimum size=0.6cm, font=\small\bfseries, inner sep=0pt}]
\node[n, fill=orange!40] (r) at (0,0) {9};
\node[n, fill=blue!12] (l) at (-1.0,-0.9) {5}; \node[n, fill=green!25, thick] (rr) at (1.0,-0.9) {4};
\draw[->, thick, red!60] (r) -- (rr);
\node[font=\rmfamily\small, text=black!60, anchor=north] at (0,-1.5) {swap with the smaller child, then continue down};
\end{tikzpicture}
Build a heap in O(n): heapify
Building by repeated push is \(O(n \log n)\). But sifting down from the last internal node to the root builds a heap in \(O(n)\): most nodes are near the bottom and sift very little.
def heapify(a):
# sift_down(i) is the same downward swap used by pop():
# swap a[i] with its smaller child until the heap property holds.
n = len(a)
for i in range(n // 2 - 1, -1, -1): # last internal node up to root
sift_down(a, i, n)
return a
The sum of sift costs is \(n/2 \cdot 1 + n/4 \cdot 2 + n/8 \cdot 3 + \dots < 2n\), hence \(O(n)\). Python’s heapq.heapify does this.
Using Python’s heap
Python’s heapq is a min-heap. For a max-heap, negate values.
import heapq
h = [5, 1, 9, 3]
heapq.heapify(h) # O(n): [1, 3, 9, 5]
heapq.heappush(h, 2) # insert
smallest = heapq.heappop(h) # extract min
top3 = heapq.nlargest(3, [5, 1, 9, 3, 8]) # [9, 8, 5]
heapq.nlargest/nsmallest maintain a heap of size \(k\), which is \(O(n \log k)\) — better than sorting when \(k\) is small.
Pattern 1: top-k and k-th largest
To find the \(k\) largest items in a stream, keep a min-heap of size \(k\). Push each item; if the heap exceeds \(k\), pop the smallest. Whatever remains is the \(k\) largest.
import heapq
def k_largest(nums, k):
heap = []
for x in nums:
heapq.heappush(heap, x)
if len(heap) > k:
heapq.heappop(heap) # drop the smallest
return heap # the k largest, in a min-heap
This is \(O(n \log k)\) time and \(O(k)\) space — the right approach when the data does not fit in memory (streaming top-k). The \(k\)-th largest is simply the root of that heap.
Pattern 2: merge k sorted lists
Put the head of each list into a min-heap; repeatedly pop the smallest and push its successor. This is \(O(N \log k)\) for \(N\) total elements, versus \(O(Nk)\) for scanning all lists each step.
import heapq
def merge_k(lists):
heap = [(lst[0], i, 0) for i, lst in enumerate(lists) if lst]
heapq.heapify(heap)
out = []
while heap:
val, li, idx = heapq.heappop(heap)
out.append(val)
if idx + 1 < len(lists[li]):
heapq.heappush(heap, (lists[li][idx + 1], li, idx + 1))
return out
The index pair breaks ties so tuples never compare the lists themselves.
Pattern 3: running median with two heaps
Keep the smaller half in a max-heap and the larger half in a min-heap, balanced so their sizes differ by at most one. The median is at one or both roots.
import heapq
class Median:
def __init__(self):
self.low, self.high = [], [] # low: max-heap (negated), high: min-heap
def add(self, x):
heapq.heappush(self.low, -x)
heapq.heappush(self.high, -heapq.heappop(self.low)) # move max to high
if len(self.high) > len(self.low):
heapq.heappush(self.low, -heapq.heappop(self.high))
def median(self):
if len(self.low) > len(self.high):
return -self.low[0]
return (-self.low[0] + self.high[0]) / 2
Two heaps give \(O(\log n)\) insert and \(O(1)\) median, versus \(O(n \log n)\) re-sorting per query. This is the “two heaps” interview pattern (Chapter 28).
Pattern 4: graph algorithms
Heaps power the greedy graph algorithms: Dijkstra and Prim repeatedly extract the node with the smallest tentative distance via a min-heap (Chapters 21–22). Without a heap, those algorithms degrade to \(O(V^2)\).
Pitfalls
- Swapping with the wrong child. Sift down must use the smaller child (min-heap) or the heap property breaks.
- Building with repeated pushes. That is \(O(n \log n)\); use
heapifyfor \(O(n)\). - Assuming search is fast. Finding an arbitrary value in a heap is \(O(n)\); heaps only give the root cheaply.
- Popping from an empty heap. Guard the size;
heapq.heappop([])raises. - Tuples with equal keys. When pushing tuples, include a unique tie-breaker, or comparison falls through to the second element and can error.
Why is a heap’s array representation possible, and what is the cost of peek, push, and pop? Why does a size-\(k\) heap give the \(k\) largest?
ASolution
A binary heap is a complete tree, so its levels map directly to a contiguous array with \(2i+1\)/\(2i+2\) children. Peek is \(O(1)\) (the root), push and pop are \(O(\log n)\) (one sift). A min-heap of size \(k\) keeps the \(k\) largest by evicting the smallest each time it grows past \(k\).
Next: AVL Trees and Balanced Trees (DSA #12) — restoring balance after every change.