General
Heap/Priority Queue problems - when to recognize you need one
7/23/2025
10
The clue that you need a heap is usually in the problem statement:
- "Find the K largest/smallest elements" → Min/Max heap
- "Merge K sorted lists/arrays" → Min heap
- "Median of a data stream" → Two heaps
- "Schedule tasks with priorities" → Max heap
- "Closest points to origin" → Max heap of size K
Common mistake: Using sorting when a heap would be more efficient.
- Sorting: O(n log n)
- Heap of size K: O(n log K) — better when K << n
Python's heapq makes implementation trivial.
heappriority-queuepatternsdsa