DSA Master › Topic 9
Queue, Deque & Heap
A heap gives you the min or max element in O(log n) per operation. For top-K, keep a heap of size K. For a running median, use two heaps (a max-heap for the lower half, a min-heap for the upper half). For K-way merges, push the head of each list.
Concepts
- PriorityQueue
- Min/max heaps
- Two heaps
- Top-K
- Deque
How to recognise it
- The problem asks for the K largest, smallest, closest or most frequent items.
- You need the median or extremes of a stream of data.
- You're merging K sorted things, or always processing the most urgent item next.
Common pitfalls
- For top-K largest, use a min-heap of size K. That's the counter-intuitive part.
- Don't build heap comparators with subtraction. Use Integer.compare.
Problems
- Implement Queue using Stacks (Easy)
- Kth Largest Element in an Array (Medium)
- Find Median from Data Stream (Hard)
- Merge k Sorted Lists (Hard)
- Task Scheduler (Medium)
- K Closest Points to Origin (Medium)
- Reorganize String (Medium)
- Find K Pairs with Smallest Sums (Medium)