Heap
Top-K, two heaps for medians, k-way merges and greedy scheduling with priority queues.
DSAIntermediate19 hrs5 patterns · 26 problems
0%
your progressCore idea
A binary heap gives O(log n) push/pop of the min. For top-k largest, keep a min-heap of size k and evict the smallest.
Reach for it when
- Top-k / k-th largest
- Merging k sorted streams
- Running median (two heaps)
- Greedy scheduling by earliest end or highest priority
Template
import heapq
def top_k(nums, k):
heap = []
for x in nums:
heapq.heappush(heap, x)
if len(heap) > k:
heapq.heappop(heap)
return sorted(heap, reverse=True)Complexity
O(n log k) for top-k; O(N log k) to merge k lists of N total items.
Common pitfalls
- Python heapq is a min-heap — negate for max
- Comparing tuples with non-comparable payloads (add a tie-breaker)
- Rebuilding the heap each step instead of pushing/popping
Patterns in this course
Recognition cues
Top KTwo HeapsMerge K SortedMinimum/Maximum Selection