Algorithmsheap usage
Heap Usage Patterns
TT
Testlaa Team
May 14, 2026•1 min read
Running top-k, merge k sorted lists, median from two heaps.
Try this in Python
import heapq
nums = [3, 1, 4, 1, 5, 9]
print(heapq.nlargest(3, nums))
Key takeaways
nlargestis fine for small k; heap of size k for streaming.- Store tuples
(priority, tie_breaker, obj)to avoid dict compares. - Lazy deletion pattern uses stale entries + checks.
Tags:
HeapsPythonStudents
