Heaps and Priority Queues
A heap always gives you the smallest item quickly. Adding and removing cost O(log n). Python's heapq module turns a list into a min-heap.
A heap always knows its smallest (or largest) item, and adding or removing takes only O(log n). That makes it perfect for "top K" questions, scheduling by priority, and merging sorted lists. Python's heapq module gives you a min-heap.
Example
Top K items
Example
Merge sorted lists
Example
For a max-heap in Python, push negative numbers:
heappush(h, -x), and flip the sign when you pop.Key points
- heapq is a min-heap: heappush and heappop.
- Keep a heap of size k for top-K problems.
- Negate values for a max-heap.
📝 Test yourself
1. What does heapq.heappop return?
2. To keep the k largest numbers, the heap size stays...
3. Fill in the function that returns the 3 biggest items:
heapq.(3, nums)
