AlgoViz

Priority queues

medium 18 min

A 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

0:00 / 6:30

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.

Step 1 of 3

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. O(log⁡n)O(\log n) on a heap.

  • dequeue()

    Remove and return the highest-priority item. O(log⁡n)O(\log n) on a heap.

  • peek()

    Return the highest-priority item without removing it. O(1)O(1).

  • is_empty() / size()

    Check whether anything is waiting, or how many. O(1)O(1).

Life of an entry
  1. 1EnqueueAdd with a priority, O(log n)
  2. 2HeapMost urgent waits at the root, peek O(1)
  3. 3DequeueExtract the root, O(log n)

Arrival order never decides who leaves next: only priority does.

Compared

Queue order versus priority order

ArrivalPriorityFIFO queue servesPriority queue serves
A11st3rd
B92nd1st
C53rd2nd
Same arrivals, A then B then C. A FIFO queue ignores priority (A, B, C); a max-priority queue serves B, C, A.

Which element leaves next?

A queue and a stack decide by time. A priority queue decides by key, and needs a rule for ties.

Worked example: ER triage (1 = minor, 5 = critical)

  1. 1

    Alice arrives, priority 3

    She is the only patient, so she is the root. Heap: [Alice 3].

  2. 2

    Bob arrives, priority 5

    He joins at index 1 and bubbles above Alice, since 5>35 > 3. Heap: [Bob 5, Alice 3]. He will be treated first although he came second.

  3. 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. 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. 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

Structureinsertextract maxpeekchange keybuild from nn
Unsorted arrayO(1)O(1)O(n)O(n)O(n)O(n)O(1)O(1) given the slotO(n)O(n)
Sorted arrayO(n)O(n)O(1)O(1)O(1)O(1)O(n)O(n)O(nlog⁡n)O(n \log n)
Balanced BSTO(log⁡n)O(\log n)O(log⁡n)O(\log n)O(log⁡n)O(\log n), O(1)O(1) cachedO(log⁡n)O(\log n)O(nlog⁡n)O(n \log n)
Binary heapO(log⁡n)O(\log n)O(log⁡n)O(\log n)O(1)O(1)O(log⁡n)O(\log n) with an index mapO(n)O(n)
Fibonacci heapO(1)O(1) amortisedO(log⁡n)O(\log n) amortisedO(1)O(1)O(1)O(1) amortised decreaseO(n)O(n)
The sorted array's insert finds its slot in O(log⁡n)O(\log n) by binary search, but shifting the rest costs O(n)O(n). Fibonacci heaps win on paper for Dijkstra but lose in practice to the simple binary heap's constants.

n inserts followed by n extracts

∑k=1nO(1)+∑k=1nO(k)⏟unsorted array=O ⁣(n(n+1)2)=O(n2)2∑k=1nO(log⁡k)⏟binary heap=O(log⁡n!)=O(nlog⁡n)\underbrace{\sum_{k=1}^{n} O(1) + \sum_{k=1}^{n} O(k)}_{\text{unsorted array}} = O\!\left(\tfrac{n(n+1)}{2}\right) = O(n^2) \qquad \underbrace{2\sum_{k=1}^{n} O(\log k)}_{\text{binary heap}} = O(\log n!) = O(n \log n)
At n=1,000n = 1{,}000 the unsorted array does about 500,500 scan steps; the heap about 2log⁡21000!≈17,0002 \log_2 1000! \approx 17{,}000 sift levels. A sorted array is O(n2)O(n^2) too, paid on the insert side.

Which implementation?

The mix of operations decides. For the usual mix of many inserts and many extracts, the binary heap wins.

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 ii are 2i+12i + 1 and 2i+22i + 2, the parent is ⌊(i−1)/2⌋\lfloor (i - 1)/2 \rfloor. 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

Both loops walk one root-to-leaf path, at most ⌊log⁡2n⌋\lfloor \log_2 n \rfloor levels.
Python
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 0
A max-priority queue from scratch: the classic interview ask. Run it.
Edit and run it in your browser

In Python

heapq and the tie-breaking counter

Python's heapq turns a plain list into a min-heap with heappush, heappop, heapify (O(n)O(n)), 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.

Python
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']
A fair priority queue: highest first, and equal priorities leave in arrival order (Bob before Diana).
Edit and run it in your browser

Built-in priority queues

LanguageClass or moduleDefaultOther direction
Pythonheapq on a list (also queue.PriorityQueue, thread-safe)Min-heapNegate the priority
JavaPriorityQueue<E>Min-heapComparator.reverseOrder()
C++std::priority_queue<T>Max-heapstd::greater<T> for min
JavaScriptNone built inWrite a heap or use a library
C++ is the odd one out: its default pops the largest value.

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 O(log⁡n)O(\log n). The hard part is finding the item: a plain heap needs an O(n)O(n) scan, unless you keep a dictionary from item to index and update it on every swap.

Two ways to change a priority

The right branch is lazy deletion: stale entries stay in the heap until they surface, costing a little memory but no searching.
Python
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 email
Lazy deletion with heapq: change and remove in O(log n) without ever searching the heap.
Edit and run it in your browser

Application

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

The same loop drives job queues, print servers with VIP jobs and game event queues.
Python
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']
Tasks arrive and run interleaved: the security alert jumps the queue, then the update does.
Edit and run it in your browser

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

Instead of decrease-key, push a new entry and skip the stale one later: lazy deletion again.

Running time with a binary heap

T(V,E)=O(E)⏟pushes⋅O(log⁡E)+O(E)⏟pops⋅O(log⁡E)=O((V+E)log⁡V)T(V, E) = \underbrace{O(E)}_{\text{pushes}} \cdot O(\log E) + \underbrace{O(E)}_{\text{pops}} \cdot O(\log E) = O\big((V + E) \log V\big)
Since E≤V2E \le V^2, log⁡E≤2log⁡V\log E \le 2 \log V, so log⁡E\log E and log⁡V\log V are the same order. Scanning an array for the minimum instead costs O(V2)O(V^2), better only for very dense graphs.

Pattern

Merge k sorted lists

k-way merge

The smallest remaining value overall must be the head of some list, and the heap holds exactly the heads.

Cost for N values in k lists

T=O(k)⏟heapify heads+N⋅O(log⁡k)⏟pop + push=O(Nlog⁡k)vsO(Nlog⁡N) concatenate and sort,   O(Nk) merge one list at a timeT = \underbrace{O(k)}_{\text{heapify heads}} + N \cdot \underbrace{O(\log k)}_{\text{pop + push}} = O(N \log k) \quad \text{vs} \quad O(N \log N) \text{ concatenate and sort, } \; O(Nk) \text{ merge one list at a time}
Memory is O(k)O(k) for the heap beyond the output. External sorting merges huge sorted runs from disk this way, and Python ships it as heapq.merge.
Python
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, lazily
The list index in each tuple says where to fetch the next value and stops lists from being compared on ties.
Edit and run it in your browser

Pattern

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 O(log⁡k)O(\log k) if it gets in.
  • O(nlog⁡k)O(n \log k) time, O(k)O(k) 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: O(nlog⁡n)O(n \log n), needs all data at once.
  • Heapify all n then pop k: O(n+klog⁡n)O(n + k \log n), O(n)O(n) memory.
  • Fine for a one-off on a small list; wasteful on a large stream.
  • Quickselect averages O(n)O(n) but is not incremental.

Why size k beats size n

nlog⁡2k  ≪  nlog⁡2nwhen k≪n:n=106,  k=10  ⇒  3.3×106 vs 2×107n \log_2 k \;\ll\; n \log_2 n \quad \text{when } k \ll n: \qquad n = 10^6,\; k = 10 \;\Rightarrow\; 3.3 \times 10^6 \text{ vs } 2 \times 10^7
Each heap operation pays the log of the heap's size, so keeping the heap at size kk is what makes it cheap.
Python
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]
Top 3 of a stream. heapq.nlargest uses the same idea.
Edit and run it in your browser

Pattern

Running median with two heaps

add(x) keeps two halves balanced

Passing every value through low and then high guarantees nothing in low is bigger than anything in high.

The invariants and the median

max⁡(low)≤min⁡(high),0≤∣low∣−∣high∣≤1,median={max⁡(low)n oddmax⁡(low)+min⁡(high)2n even\max(\text{low}) \le \min(\text{high}), \qquad 0 \le |\text{low}| - |\text{high}| \le 1, \qquad \text{median} = \begin{cases} \max(\text{low}) & n \text{ odd} \\[2pt] \dfrac{\max(\text{low}) + \min(\text{high})}{2} & n \text{ even} \end{cases}
Each add does at most three heap operations: O(log⁡n)O(\log n). Reading the median touches only the two roots: O(1)O(1). Re-sorting after each add would cost O(nlog⁡n)O(n \log n) every time.
Python
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())
Stream 3, 1, 5, 4, 2: medians 3, 2.0, 3, 3.5, 3. heapq has no max-heap, so low stores negated values.
Edit and run it in your browser

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 O(1)O(1).
  • 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 O(log⁡n)O(\log n) (append, sift up), dequeue O(log⁡n)O(\log n) (last to root, sift down), peek O(1)O(1), build O(n)O(n).
  • Unsorted and sorted arrays each make one side O(n)O(n), so nn inserts plus nn extracts cost O(n2)O(n^2) against the heap's O(nlog⁡n)O(n \log n).
  • In Python push (-priority, counter, item) into heapq: 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 O((V+E)log⁡V)O((V + E) \log V), merge k lists O(Nlog⁡k)O(N \log k), top-k O(nlog⁡k)O(n \log k) with a min-heap, running median with two heaps in O(log⁡n)O(\log n) per value.

Sources