Python Snippet

heapq Min-Heap Recipes

Difficulty: Medium

Python's `heapq` module turns any list into a binary min-heap in place, supporting O(log n) push and pop. It is the priority-queue primitive that powers Dijkstra, Top-K, and merging sorted streams. This snippet covers the basic push and pop, the Top-K largest pattern using `nsmallest` and `nlargest`, and the merge of multiple sorted iterables in O(N log K).