🐍 Python Intermediate

What is Python's heapq module?

Why Interviewers Ask This

Candidates at the intermediate level are expected to not only know this concept but explain the trade-offs involved. Interviewers use this question to see if you can reason about design decisions, not just recall facts.

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.

Pro Tip

Demonstrate both theoretical understanding and practical experience. Say what it is, then give an example of how you actually used it in a Python codebase.