Heaps / Priority Queues
Always know the smallest (or largest) item, at O(log n) per update.
- visited / done
- active this step
- removed / popped
- result
Fill the heap to size k
Push 3 and 2. The heap holds the 2 largest values seen so far.
VARIABLES
- x
- 2
- heap
- [2, 3]
Intuition & complexity
The core mental model, trade-offs, and Big-O cost.
What it is
A binary heap is a complete tree stored in an array where every parent is ≤ its children (a min-heap). Python’s heapq module is a min-heap.
Why it matters
Top-k, scheduling and merging problems need the next best item again and again without sorting everything.
Think of it like this
An emergency room: the most urgent patient is seen next, whoever arrived first.
Use it when
- Top k, or the kth largest or smallest
- Merging k sorted lists
- Always taking the cheapest option next (Dijkstra)
Avoid it when
- You need everything in sorted order once - just sort
- You need fast search for arbitrary values
Complexity cheatsheet
| Operation | Time | Space |
|---|---|---|
| Push or pop | O(log n) | O(1) |
| Peek the minimum | O(1) | O(1) |
| heapify a list | O(n) | O(1) |
Often confused with: binary search trees - they keep full order; a heap only guarantees the root is the minimum.
How to recognize it
Clues in interview prompts that point straight to this pattern.
- A heap of size k gives O(n log k) for top-k
- heapq is min-only - push negated values for a max-heap
Mistakes & edge cases
Catch common off-by-one bugs and corner cases before submitting.
Common mistakes
- Pushing all n items into a max-heap - O(n log n) instead of O(n log k)
- Forgetting heapq is a min-heap
- Pushing tuples whose second item can’t be compared when the first items tie
Edge cases to test
- k = 1 or k = n
- Duplicates
- Negative numbers
Knowledge check
Quick check to lock in the intuition.
Keeping a min-heap of size k while scanning n numbers costs…
Practice
Apply what you just watched on real interview problems.