Priority queues
medium 18 minA priority queue serves the item with the highest (or lowest) priority first, whatever order items arrived in.
Video lesson · Chapter 1 of 7
The last arrival can go first
Priority queues — The backstage print queue
1:27Reel
Read caption
Ada serves the most urgent backstage print job, breaking ties by arrival sequence. Sort decisions by priority first, then break ties by arrival.
How it works
Step through the idea, or press Play.
Enqueue with a priority. Every item carries a priority; it joins the heap at the end and sifts up to its level in O(log n)
Understand it
Start here
What a priority queue is
A priority queue is an abstract data type in which every element has a priority, and elements are served by priority rather than by arrival. Think of a hospital emergency room: a patient with a critical condition is treated before someone with a sprain, even if they walked in later. A plain queue would treat them in arrival order, which could be fatal.
enqueue(item, priority)
Insert an item with its priority. on a heap.
dequeue()
Remove and return the highest-priority item. on a heap.
peek()
Return the highest-priority item without removing it. .
is_empty() / size()
Check whether anything is waiting, or how many. .
- 1EnqueueAdd with a priority, O(log n)
- 2HeapMost urgent waits at the root, peek O(1)
- 3DequeueExtract the root, O(log n)
Arrival order never decides who leaves next: only priority does.
Compared
Queue order versus priority order
| Arrival | Priority | FIFO queue serves | Priority queue serves |
|---|---|---|---|
| A | 1 | 1st | 3rd |
| B | 9 | 2nd | 1st |
| C | 5 | 3rd | 2nd |
Which element leaves next?
Worked example: ER triage (1 = minor, 5 = critical)
- 1
Alice arrives, priority 3
She is the only patient, so she is the root. Heap:
[Alice 3]. - 2
Bob arrives, priority 5
He joins at index 1 and bubbles above Alice, since . Heap:
[Bob 5, Alice 3]. He will be treated first although he came second. - 3
Charlie arrives, priority 1
He joins at index 2 under Bob and stays. Heap:
[Bob 5, Alice 3, Charlie 1]. Order so far: Bob, Alice, Charlie. - 4
A doctor is free: dequeue
Bob leaves. Charlie (the last entry) fills the root and sinks below Alice. Heap:
[Alice 3, Charlie 1]. - 5
Diana arrives, priority 5
She joins at index 2 under Alice and bubbles to the root. Heap:
[Diana 5, Charlie 1, Alice 3]. Treatment order: Diana, Alice, Charlie.
Implementations
Four ways to build one
| Structure | insert | extract max | peek | change key | build from |
|---|---|---|---|---|---|
| Unsorted array | given the slot | ||||
| Sorted array | |||||
| Balanced BST | , cached | ||||
| Binary heap | with an index map | ||||
| Fibonacci heap | amortised | amortised | amortised decrease |
n inserts followed by n extracts
Which implementation?
Under the hood
The binary heap engine
A binary heap is a complete binary tree stored level by level in an array: the children of slot are and , the parent is . The shape and ordering rules are covered in heap properties, and sift up and sift down step by step in heap operations. Here they are wired into the priority queue interface.
Enqueue and dequeue on a max-heap
class MaxPQ: """Max-priority queue on a binary heap stored in a list.""" def __init__(self): self.heap = [] # (priority, item) pairs def enqueue(self, item, priority): h = self.heap h.append((priority, item)) # 1. add at the end i = len(h) - 1 while i > 0 and h[i][0] > h[(i - 1) // 2][0]: # 2. sift up p = (i - 1) // 2 h[i], h[p] = h[p], h[i] i = p def dequeue(self): h = self.heap if not h: raise IndexError("dequeue from empty priority queue") top, last = h[0], h.pop() if h: h[0] = last # last entry fills the root i = 0 while True: # sift down big = i for c in (2 * i + 1, 2 * i + 2): if c < len(h) and h[c][0] > h[big][0]: big = c if big == i: break h[i], h[big] = h[big], h[i] i = big return top[1] def peek(self): if not self.heap: raise IndexError("peek from empty priority queue") return self.heap[0][1] def __len__(self): return len(self.heap)er = MaxPQ()er.enqueue("Alice", 3); er.enqueue("Bob", 5); er.enqueue("Charlie", 1)print(er.peek()) # Bobprint(er.dequeue(), er.dequeue()) # Bob Aliceer.enqueue("Diana", 5)print(er.dequeue(), er.dequeue(), len(er)) # Diana Charlie 0In Python
heapq and the tie-breaking counter
Python's heapq turns a plain list into a min-heap with heappush, heappop, heapify (), heapreplace, nlargest and nsmallest. It compares whole entries, so you push tuples: (-priority, counter, item). Negating gives highest-first; the counter, a number that only ever grows, breaks ties in arrival order so the item itself is never compared.
import heapqfrom itertools import countclass PriorityQueue: """Highest priority first; equal priorities leave in arrival order.""" def __init__(self): self._heap = [] self._tick = count() # tie-breaker def enqueue(self, item, priority): heapq.heappush(self._heap, (-priority, next(self._tick), item)) def dequeue(self): if not self._heap: raise IndexError("dequeue from empty priority queue") return heapq.heappop(self._heap)[2] def peek(self): if not self._heap: raise IndexError("peek from empty priority queue") return self._heap[0][2] def __len__(self): return len(self._heap)pq = PriorityQueue()for name, p in [("Alice", 3), ("Bob", 5), ("Charlie", 1), ("Diana", 5)]: pq.enqueue(name, p)print([pq.dequeue() for _ in range(len(pq))])# ['Bob', 'Diana', 'Alice', 'Charlie']Built-in priority queues
| Language | Class or module | Default | Other direction |
|---|---|---|---|
| Python | heapq on a list (also queue.PriorityQueue, thread-safe) | Min-heap | Negate the priority |
| Java | PriorityQueue<E> | Min-heap | Comparator.reverseOrder() |
| C++ | std::priority_queue<T> | Max-heap | std::greater<T> for min |
| JavaScript | None built in | Write a heap or use a library |
Updates
Changing priorities: decrease-key and lazy deletion
Graph algorithms and schedulers often need to change an item's priority. On a heap that is a sift: raise a priority in a max-heap and sift up, lower it and sift down, both . The hard part is finding the item: a plain heap needs an scan, unless you keep a dictionary from item to index and update it on every swap.
Two ways to change a priority
import heapqfrom itertools import countheap, tick, current = [], count(), {}def set_priority(task, priority): """Add a task or change its priority: O(log n).""" current[task] = priority heapq.heappush(heap, (-priority, next(tick), task))def pop_task(): while heap: neg_p, _, task = heapq.heappop(heap) if current.get(task) == -neg_p: # still the live entry? del current[task] return task raise KeyError("pop from empty priority queue")def remove_task(task): current.pop(task, None) # its heap entry goes staleset_priority("backup", 1); set_priority("email", 2); set_priority("report", 4)set_priority("backup", 9) # raise: the old (1, backup) entry is now staleremove_task("report")print(pop_task(), pop_task()) # backup emailApplication
Task scheduling
System: 90 to 100
Keyboard and mouse handlers, interrupts. A 100 ms delay already feels sluggish, so they always go first.
User: 50 to 80
Browsers, video players, games. They get fair CPU time once system work is done.
Background: 10 to 40
Indexing, updates, email sync. They use spare cycles.
A priority scheduler loop
import heapqfrom itertools import countready, tick = [], count()def submit(task, priority): heapq.heappush(ready, (-priority, next(tick), task))def run_next(): return heapq.heappop(ready)[2]submit("Email", 2); submit("Backup", 1); submit("SecurityAlert", 9)print(run_next()) # SecurityAlertsubmit("Update", 5)print(run_next()) # Updateprint([run_next() for _ in range(len(ready))]) # ['Email', 'Backup']Preview
Dijkstra's algorithm runs on a min-priority queue
Dijkstra finds shortest paths from one source in a graph with non-negative weights. It is breadth-first search with the FIFO queue swapped for a min-priority queue keyed by tentative distance: it always settles the closest unsettled node next. Try it in the visualizer on a five-node graph.
Dijkstra with heapq
Running time with a binary heap
Pattern
Merge k sorted lists
k-way merge
Cost for N values in k lists
heapq.merge.import heapqdef merge_k(lists): heap = [(lst[0], i, 0) for i, lst in enumerate(lists) if lst] heapq.heapify(heap) # one head per list: O(k) out = [] while heap: val, i, j = heapq.heappop(heap) # smallest head overall out.append(val) if j + 1 < len(lists[i]): # that list's next value heapq.heappush(heap, (lists[i][j + 1], i, j + 1)) return outprint(merge_k([[1, 4, 9], [2, 3, 8], [5, 6]])) # [1, 2, 3, 4, 5, 6, 8, 9]print(list(heapq.merge([1, 4, 9], [2, 3, 8], [5, 6]))) # the same, lazilyPattern
Top-k with a size-k heap
Min-heap of size k (k largest)
- Root = the weakest of the k kept: the bar a newcomer must beat.
- Each value costs one comparison, plus if it gets in.
- time, memory, works on an endless stream.
- For the k smallest, flip it: a max-heap of size k.
Heap of all n (or sort everything)
- Sort and slice: , needs all data at once.
- Heapify all n then pop k: , memory.
- Fine for a one-off on a small list; wasteful on a large stream.
- Quickselect averages but is not incremental.
Why size k beats size n
import heapqdef top_k(nums, k): heap = [] # min-heap of the k largest so far for x in nums: if len(heap) < k: heapq.heappush(heap, x) elif x > heap[0]: # beats the weakest of the k heapq.heapreplace(heap, x) # pop the root and push x return sorted(heap, reverse=True)nums = [5, 12, 3, 8, 20, 1, 9]print(top_k(nums, 3)) # [20, 12, 9]print(heapq.nlargest(3, nums)) # [20, 12, 9]print(heapq.nsmallest(2, nums)) # [1, 3]Pattern
Running median with two heaps
add(x) keeps two halves balanced
The invariants and the median
import heapqclass MedianFinder: def __init__(self): self.low = [] # max-heap (negated): the smaller half self.high = [] # min-heap: the larger half def add(self, x): heapq.heappush(self.low, -x) heapq.heappush(self.high, -heapq.heappop(self.low)) # low's max moves up if len(self.high) > len(self.low): # keep low >= high 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]) / 2mf = MedianFinder()for x in [3, 1, 5, 4, 2]: mf.add(x) print(x, mf.median())Recap
Key takeaways
Use a priority queue when
- Items must be processed by priority, not arrival order.
- You repeatedly need the current max or min while items keep arriving.
- Inserts and extracts are both frequent.
- Graph algorithms: Dijkstra, Prim, A*.
- Event-driven simulation in time order, top-k, merging sorted streams.
Avoid it when
- You need first-in, first-out: use a queue.
- All priorities are the same: a plain queue is simpler and .
- You need to search for or access arbitrary elements: use a hash map or a BST.
- You need everything in sorted order at all times: use a sorted container.
Key points
- A priority queue is an ADT that serves the highest (or lowest) priority first; a binary heap is its standard implementation.
- Heap costs: enqueue (append, sift up), dequeue (last to root, sift down), peek , build .
- Unsorted and sorted arrays each make one side , so inserts plus extracts cost against the heap's .
- In Python push
(-priority, counter, item)intoheapq: negate for max-first, count to break ties fairly. - Change priorities with an index map and a sift, or lazily: push a new entry and skip stale ones.
- Patterns: Dijkstra , merge k lists , top-k with a min-heap, running median with two heaps in per value.