Heaps & Priority Queues
Data Structures & Algorithms · Trees & Heaps · Advanced · 15 min
Always grab the smallest (or biggest) item fast: top-k, scheduling, Dijkstra.
A pyramid of people where everyone is shorter than the two people standing on their shoulders. The shortest person is always at the very top. A newcomer joins at the bottom and swaps upward until they fit; when the top person leaves, the last person climbs up and slides down.
The idea in everyday words
A hospital emergency room: patients aren't served in arrival order but by urgency. The most urgent is always at the front. A heap is that waiting room: adding a patient or taking the most urgent one takes only O(log n).
What a heap gives you
- push an item: O(log n)
- pop the smallest (min-heap): O(log n)
- peek the smallest: O(1)
Python's heapq is a min-heap on a normal list:
import heapq
h = []
for x in [5, 1, 8, 3]:
heapq.heappush(h, x)
print("pushed", x, "-> smallest is", h[0])
print("pop:", heapq.heappop(h), heapq.heappop(h))
Top-k with a size-k heap
To keep the k largest, keep a min-heap of size k; if it grows past k, pop the smallest. What remains are the k biggest. O(n log k).
import heapq
def top_k(nums, k):
h = []
for x in nums:
heapq.heappush(h, x)
if len(h) > k:
heapq.heappop(h)
return sorted(h, reverse=True)
print(top_k([7, 2, 9, 4, 11, 5], 3))
Max-heap trick in Python: push -x and negate when popping.
Building a heap in O(n) with heapify
Pushing n items one by one costs O(n log n). heapq.heapify(h) turns a whole list into a heap in O(n). It works from the bottom up: it takes each parent, starting with the last one, and sifts it DOWN until it is smaller than its children.
Why is that cheaper? Most nodes sit near the bottom, so they barely move:
- about half of the nodes are leaves: they move 0 levels,
- about a quarter move at most 1 level,
- about an eighth move at most 2 levels, and so on.
Go deeper: about n/2^(j+1) nodes have height j, and each one moves at most j levels. The total is at most n · (1/4 + 2/8 + 3/16 + ...) = n · Σ j/2^(j+1) = n · 1. So heapify does at most about n swaps: O(n).
Inside the heap: an array pretending to be a tree
A heap is stored in a plain list. The tree is only in our heads:
- the children of index i are at 2i + 1 and 2i + 2
- the parent of index i is at (i - 1) // 2
- the rule: every parent is <= its children, so the smallest item is at index 0
push puts the new item at the end, then sifts it up: swap with the parent while the parent is bigger. pop takes the root, moves the last item into the root's place, then sifts it down: swap with the smaller child while a child is smaller.
Each swap moves one level, and a heap with n items has about log₂ n levels. That is why both are O(log n).
def push(h, x):
h.append(x)
i = len(h) - 1
while i > 0 and h[(i - 1) // 2] > h[i]:
p = (i - 1) // 2
h[i], h[p] = h[p], h[i]
i = p
h = []
for x in [5, 3, 8, 1]:
push(h, x)
print("after push", x, "->", h)
Step by step
- k = 2:
nums = [7, 2, 9, 4]
- push 7, 2:
heap [2, 7]
- push 9:
size 3 > 2 → pop 2 → [7, 9]
- push 4:
pop 4 → [7, 9] = the 2 largest
Code example
import heapq
tasks = [(3, "write tests"), (1, "fix prod bug"), (2, "code review")]
heapq.heapify(tasks)
while tasks:
priority, task = heapq.heappop(tasks)
print(priority, task)Complexity
- Time: push/pop O(log n), peek O(1); k largest with a size-k heap O(n log k)
- Space: a heap of n items O(n); the size-k heap trick only keeps O(k)
Interview tips
Kth Largest Element, Top K Frequent, Merge K Lists, Median from Data Stream.
Heaps are stored as arrays: children of i are 2i+1 and 2i+2.
Challenge: K Largest Numbers
Return the k largest numbers in descending order.
Example: k_largest([7, 2, 9, 4, 11, 5], 3) → [11, 9, 7]
Solve it in the browser with tests, hints and an AI coach.
Practice problems
- Kth Largest Element in an Array (Medium)
- Last Stone Weight (Easy)
- Top K Frequent Elements (Medium)
- Find Median from Data Stream (Hard)
More in Trees & Heaps
Previous: Balanced Trees: AVL & Red-Black · Next: Tries (Prefix Trees)