A priority queue is what you get from it: a queue that always hands you the most urgent item next. Whenever a problem keeps asking for the smallest, largest, closest or earliest of a changing set (top k, merging sorted lists, Dijkstra, scheduling), a heap is usually the answer.
When to use it
- You repeatedly need the smallest or largest item while items are added and removed.
- The question asks for the k largest, k smallest, k most frequent or k closest items.
- You are merging k sorted lists or streams.
- Sorting everything would work, but you only need a few items or the data arrives over time.
The template
import heapq
def k_largest(nums, k):
heap = [] # min-heap of the k largest seen so far
for x in nums:
heapq.heappush(heap, x) # O(log k)
if len(heap) > k:
heapq.heappop(heap) # drop the smallest: not in top k
return heap # heap[0] is the k-th largest
# Python's heapq is a min-heap; push -x for a max-heap.The variants you will meet
How a heap is stored
A heap is a complete binary tree laid out level by level in an array. For index i the children are at 2i + 1 and 2i + 2 and the parent at (i - 1) // 2, so no pointers are needed.
Insert and extract
Insert appends at the end and sifts the new item up while it beats its parent. Extract moves the last item to the root and sifts it down, swapping with the smaller child, until the order holds again.
Heapify, peek and heap type
Building a heap by sifting down from the last parent to the root takes O(n), not O(n log n). Peeking reads index 0. Flipping the comparison turns a min-heap into a max-heap.
Top k and k-way merge
Keep a heap of size k and evict the worst whenever it grows past k, for O(n log k). To merge k sorted lists, keep each list's current head in a heap and pop the smallest until it is empty.
Time and space complexity
Peek is O(1); insert and extract are O(log n) because sifting walks one root-to-leaf path. Heapify is O(n). Top k over n items is O(n log k) with O(k) space, which beats sorting when k is small. Heap sort is O(n log n) in place.