Algorithmsheap usage

Heap Usage Patterns

TT
Testlaa Team
May 14, 20261 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

  • nlargest is 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