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).

Code Snippets
/

heapq Min-Heap Recipes

heapq Min-Heap Recipes

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).

Python
Medium
3 snippets
py-standard-library
heap
code-template
algorithms

586 views

17

heapq operates directly on a Python list, treating it as a binary heap with heap[0] as the smallest element. heappush and heappop are both O(log n). Note that the heap is NOT sorted: it satisfies the heap invariant (parent <= children), but the in-memory order can look scrambled. Reading heap[0] gives an O(1) min query, which is the headline operation. To sort, repeatedly pop until empty (heap sort), which is O(n log n) total.