Priority queues & heap sort
Use heaps for top-k, merging sorted lists and scheduling, and implement heap sort.
By Invicly Tech, , in Data Structures & Algorithms. About 11 minutes to read.
In short
A priority queue always hands out the highest-priority item next, and a heap is the standard implementation. In Python you use heapq on a plain list. Heaps power top-k queries, merging sorted streams, running medians, schedulers and Dijkstra's algorithm, and heap sort sorts in place in O(n log n).
Explained simply
A normal queue serves people in arrival order. A priority queue serves the most important one first, like an emergency room that treats the most serious case next, no matter who arrived first. You can add items at any time, and you can always take out the current most important one.
A heap is the usual way to build one, because adding and removing both take about log n steps. In Python, you use the heapq module on a normal list.
Priority queues solve many everyday problems. Find the 10 biggest numbers in a stream of millions without sorting it all. Merge many sorted lists into one. Keep track of the middle value as numbers keep arriving. Decide which job a computer should run next.
There is even a sorting algorithm built on a heap, called heap sort. It builds a heap, then repeatedly takes out the top. It sorts in place in O(n log n) time, but it is not stable.
Press Play on a diagram to walk through it one step at a time.
- Step 1Push x
Add to the heap.
- Step 2Too big?
If size exceeds k, pop the minimum.
- Step 3Repeat
For every element.
- Step 4Result
Heap holds the k largest.
- sorted(a)[-k:]
- O(n log n)
- O(n) memory
- Best when k is close to n
- heapq.nlargest(k, a)
- O(n log k)
- O(k) memory, works on streams
- Best when k is small
- Partition around pivots
- Expected O(n)
- Needs the whole array, reorders it
- Top k come out unsorted
In depth
Top-k: choosing the right tool
To keep the k largest of n items, use a min-heap of size k. Its root is the smallest of the current top k, the first to be evicted. For each new item x: if the heap has fewer than k items, push x; otherwise if x > h[0], call heapreplace(h, x). That is O(n log k) time and O(k) memory, and it works on a stream you cannot store.
heapq.nlargest(k, iterable) and heapq.nsmallest(k, iterable) do exactly this, and accept key=. They are best when k is small compared with n. When k is close to n, sorted(iterable)[:k] is simpler and faster. For k = 1, use max() or min().
Quickselect finds the k-th element in expected O(n) but needs the whole array in memory and reorders it. Heaps win for streams and when you need the top k items in order.
- Stream top-k: size-k min-heap, O(n log k), O(k) memory
- nlargest / nsmallest accept key=
- k close to n: just sort
Merging k sorted lists
Put the first item of each list into a heap as (value, list index, position). Pop the smallest, output it, and push the next item from the same list. The heap never holds more than k entries, so each of the N total items costs O(log k): O(N log k) overall.
The list index in the tuple serves two purposes: it tells you where to get the next item, and it breaks ties so Python never compares the payloads, which might not be comparable (linked list nodes, for example).
heapq.merge(*iterables) does this lazily and supports key= and reverse=. Merging is how external sorting combines sorted chunks on disk, how databases merge sorted runs, and how log-structured storage engines compact sorted files.
Compare with merging the lists pairwise one after another: that costs O(N k) in the worst case. Merging pairs in rounds (like merge sort) also reaches O(N log k).
- Lists to Heap: push heads 1, 2, 31push heads 1, 2, 3
- Heap to Output: pop 12pop 1
- Lists to Heap: push 4 from list 03push 4 from list 0
- Heap to Output: pop 24pop 2
- Lists to Heap: push 5 from list 15push 5 from list 1
- Heap to Output: pop 3, 4, 5 in order6pop 3, 4, 5 in order
Running median with two heaps
Keep the smaller half of the numbers in a max-heap (low) and the larger half in a min-heap (high). Maintain two rules: every number in low is at most every number in high, and the sizes differ by at most one (say low may have one extra).
To add x: push it onto low, then move low's largest to high (this enforces the ordering rule). If high now has more items than low, move high's smallest back to low. Each add is a constant number of heap operations, O(log n).
The median is then the top of low if it has more items, or the average of both tops if the sizes are equal, which is O(1). With heapq, low stores negated values.
The same two-heap idea works for sliding-window medians, combined with lazy deletion for numbers that leave the window.
- Step 1Add 5
low [5], high []. Median 5.
- Step 2Add 15
low [5], high [15]. Median 10.
- Step 3Add 1
low [5, 1], high [15]. Median 5.
- Step 4Add 3
low [3, 1], high [5, 15]. Median 4.
Scheduling and event simulation
Many scheduling problems sort events by start time and keep a heap of end times. For the minimum number of meeting rooms: sort meetings by start. For each meeting, if the earliest ending meeting (h[0]) has ended by this start, reuse that room with heapreplace; otherwise push a new room. The heap size at the end is the answer. Time O(n log n).
Operating systems, game engines and simulations keep a priority queue of future events ordered by time: pop the next event, process it, push any new events it creates. Timers in event loops like asyncio work this way, keeping scheduled callbacks in a heap.
Two practical notes. If several threads share a queue, use queue.PriorityQueue, which wraps heapq with locking. And to cancel or reprioritise items in heapq, mark the old entry as removed and skip it when popped, as recommended in the heapq documentation.
- Meeting rooms: heap of end times, O(n log n)
- Event loop: pop earliest event, push new ones
- Threads: queue.PriorityQueue
Heap sort in place
Build a max-heap from the array in O(n) with bottom-up heapify. The largest item is now at index 0. Swap it with the last item, shrink the heap size by one, and sift the new root down. The largest item is now in its final place at the end. Repeat until the heap is empty.
Each of the n - 1 extraction steps costs O(log n), so heap sort is O(n log n) in the best, average and worst case, using O(1) extra memory. That combination (guaranteed n log n and in place) is why introsort uses heap sort as its fallback.
Downsides: it is not stable, because the swaps move items over long distances. And its memory access jumps around the array, so on modern CPUs it is usually slower than quicksort and merge sort. Python's sorted() is faster still for everyday use.
Learn it in 5 short steps
About 35m each. Track them with a timer in your plan.
- 1Use heapq for push and pop~35m
- 2Find top-k elements with a size-k heap~35m
- 3Merge k sorted lists~35m
- 4Track a running median with two heaps~35m
- 5Implement heap sort~35m
Key points
- Top-k with a size-k heap: O(n log k) time, O(k) space.
- Merge k sorted lists: O(N log k) with one heap entry per list.
- Running median: max-heap of lower half, min-heap of upper half.
- Heap sort: O(n log n), in place, not stable.
Key terms
Tap a card to flip it. 0/4 known
Examples
import heapq
def top_k(nums, k): # O(n log k)
h = []
for x in nums:
heapq.heappush(h, x)
if len(h) > k:
heapq.heappop(h)
return sorted(h, reverse=True)
def merge_sorted(lists): # O(N log k)
return list(heapq.merge(*lists))
print(top_k([3, 1, 5, 12, 2, 11], 3)) # [12, 11, 5]
print(merge_sorted([[1, 4], [2, 5], [3]]))Running median class
We add 5, 15, 1 and 3 and print the median after each. low is a max-heap via negation and high is a min-heap. The add method pushes through low into high to keep the order rule, then rebalances so low has the same number of items or one more. Medians: 5, 10.0, 5, 4.0.
import heapq
class RunningMedian:
def __init__(self): self.low, self.high = [], [] # low stores -x
def add(self, x):
heapq.heappush(self.high, -heapq.heappushpop(self.low, -x))
if len(self.high) > len(self.low):
heapq.heappush(self.low, -heapq.heappop(self.high))
def median(self):
if len(self.low) > len(self.high): return -self.low[0]
return (-self.low[0] + self.high[0]) / 2
rm = RunningMedian()
for x in [5, 15, 1, 3]:
rm.add(x); print(rm.median(), end=' ') # 5 10.0 5 4.0Heap sort in place
For [4, 10, 3, 5, 1], heapify into the max-heap [10, 5, 3, 4, 1]. Swap 10 to the end and sift down within the first four items, then swap 5 into place, and so on. After n - 1 rounds the array is ascending. Memory use is O(1) beyond the input.
def sift_down_max(a, i, n):
while (c := 2 * i + 1) < n:
if c + 1 < n and a[c + 1] > a[c]: c += 1
if a[i] >= a[c]: break
a[i], a[c] = a[c], a[i]; i = c
def heap_sort(a):
n = len(a)
for i in range(n // 2 - 1, -1, -1):
sift_down_max(a, i, n)
for end in range(n - 1, 0, -1):
a[0], a[end] = a[end], a[0]
sift_down_max(a, 0, end)
return a
print(heap_sort([4, 10, 3, 5, 1])) # [1, 3, 4, 5, 10]Quick reference
- k largest: size-k min-heap or heapq.nlargest(k, a), O(n log k)
- Merge k sorted lists: heap of (value, list_id, pos), O(N log k)
- Running median: max-heap low half, min-heap high half, sizes differ by at most 1
- Meeting rooms: sort by start, heap of end times; answer is the heap size
- Heap sort: heapify O(n), then n - 1 pops O(log n) each; in place, not stable
- Thread-safe priority queue: queue.PriorityQueue
- Cancel an entry: mark it removed and skip it when popped
Common mistakes
- Pushing tuples whose second field is not comparable when priorities tie.
- Sorting the whole array when only the top k items are needed.
Quick quiz
Pick an answer to see if you're right and why.
Practice exercises
Try each one yourself first. Use the hint if you get stuck, then compare with the solution.
- Exercise 1easy
Use heapq.nsmallest with a key to find the 2 points closest to the origin. Example: [(1, 3), (-2, 2), (5, 8), (0, 1)] gives [(0, 1), (-2, 2)].
- Exercise 2medium
Write min_meeting_rooms(meetings) for a list of (start, end) pairs, where a meeting ending at t frees its room for one starting at t. Example: [(0, 30), (5, 10), (15, 20)] needs 2 rooms.
- Exercise 3hard
Write reorganize(s) that rearranges a string so no two adjacent characters are equal, or returns '' if impossible. Example: 'aab' gives 'aba'; 'aaab' gives ''.
Check yourself
Answer in your head, reveal, then be honest with yourself.
Feel confident about this topic?
Frequently asked questions
- What is the difference between a priority queue and a heap?
- A priority queue is the idea: insert items and remove the best one. A heap is one data structure that implements it efficiently; a sorted list or balanced tree could also implement it.
- Should I use heapq or queue.PriorityQueue?
- Use heapq in normal single-threaded code; it is faster and more flexible. Use queue.PriorityQueue when several threads put and get items, because it handles locking.
- How do I update an item's priority in heapq?
- heapq cannot change priorities in place. Push a new entry with the new priority and mark or ignore the old one when it is popped.