What is Python's heapq module?
Answer
The heapq module implements a min-heap using a regular Python list. The heap property guarantees that heap[0] is always the smallest element. Key functions: heapq.heappush(heap, item) — add an item (O(log n)). heapq.heappop(heap) — remove and return the smallest item (O(log n)). heapq.heappushpop(heap, item) — push then pop (more efficient than separate calls). heapq.heapify(list) — convert a list to a heap in O(n). heapq.nlargest(n, iterable) and heapq.nsmallest(n, iterable) — efficiently find the n largest/smallest without full sort. For a max-heap, negate values: heappush(heap, -value). Use heapq for: priority queues (Dijkstra's algorithm, A* search), efficiently finding k-th smallest/largest elements, and any scenario requiring "get the minimum quickly" without full sorting.