Heap / Priority Queue Pattern
A heap keeps the min or max element accessible in O(1) and inserts/removes in O(log n). It's the backbone of 'top-k', streaming medians, and greedy schedulers.
Typical complexity: O(log n) per push/pop; O(n log k) for top-k
When to use it
- You need the k largest/smallest, or a running median.
- You repeatedly pull the current best candidate (Dijkstra, scheduling).
- You're merging multiple sorted streams.
Practice problems
Read the approach or generate an interactive, step-by-step lesson:
Deep dive
Heap Pattern: When a Priority Queue Beats Sorting Everything
Learn when heaps are the right data structure, how min-heaps and max-heaps work, and why they shine in top-k and streaming problems.
Master heap / priority queue by doing
codebrew.ai turns each problem into an interactive lesson — trace the algorithm variable by variable until the pattern clicks.
Start a free lesson