Heap & Priority Queue — the shape behind dozens of interview problems.
TL;DR
A data structure that returns the min or max in O(log n) per operation. Insert/pop O(log n); peek O(1); heapify O(n).
When to reach for Heap & Priority Queue
- Top-K or k-th largest queries.
- Merge-K sorted streams.
- Scheduling the earliest-available resource.
Scenario variants (legal, original)
- Leaderboard Live-Rank — top-k scores as events stream.
- Barista Rotation — next free barista among k.
- Multi-Feed Merger — k-way merge of sorted feeds.
Heap & Priority Queue in Python
import heapq
def k_largest(nums: list[int], k: int) -> list[int]:
heap: list[int] = []
for v in nums:
if len(heap) < k:
heapq.heappush(heap, v)
elif v > heap[0]:
heapq.heapreplace(heap, v)
return heapSee language-specific tabs at /languages/python/patterns and the SQL variant at /languages/sql/patterns.
Common bugs
- Forgetting Python's heapq is a min-heap (negate for max).
- Pushing the full array then popping k — wastes O(n log n) vs O(n log k).
- Tie-breaking with non-comparable payloads — wrap in a tuple with a counter.
Related patterns
Frequently asked questions
- What is the heap & priority queue pattern?
- Heap & Priority Queue is a data structure that returns the min or max in o(log n) per operation. Insert/pop O(log n); peek O(1); heapify O(n).
- When should I use heap & priority queue?
- Use it when: Top-K or k-th largest queries. Merge-K sorted streams. Scheduling the earliest-available resource.
- What are the most common heap & priority queue bugs?
- Forgetting Python's heapq is a min-heap (negate for max). Pushing the full array then popping k — wastes O(n log n) vs O(n log k). Tie-breaking with non-comparable payloads — wrap in a tuple with a counter.
- What problems use the heap & priority queue pattern?
- Representative scenarios: Leaderboard Live-Rank — top-k scores as events stream. Barista Rotation — next free barista among k. Multi-Feed Merger — k-way merge of sorted feeds.
- Is heap & priority queue on the Blind 75?
- Yes — Heap & Priority Queue is one of the core patterns behind the Blind 75 list. See /blind-75 for the complete mapping.
Run the free diagnostic.
Ten-minute patterns quiz. No card. Personalized loop starts on the other side.