Priority Queues
A priority queue is an abstract data type that always removes the item with the highest priority, not the one that arrived first. A binary heap is the usual way to build it: O(log n) insert and extract, O(1) peek.
Ordered by Priority, Not Arrival
A priority queue is an abstract data type in which every item carries a priority, and the item removed is always the one with the highest priority, whenever it was inserted. It has a queue's interface but not a queue's order: it breaks the FIFO rule of an ordinary queue on purpose.
The interface is small. insert (also push, offer) adds an item with a priority. extract (also pop, poll) removes and returns the highest-priority item. peek (or top) reads it without removing it. Some versions add decrease-key, which changes an item's priority in place.
The abstract type and its implementation are easy to mix up, because the names are used loosely. A priority queue is the contract; a heap is the data structure that almost always provides it. Courses teach heaps and priority queues together for that reason. C++ makes the split explicit: std::priority_queue is an adapter that runs heap operations over a container.
Note what the type does not promise: no order among equal priorities, no way to walk the items in priority order without removing them, and no fast search for an arbitrary item. A priority queue answers one question, which item is most urgent, and anything else costs O(n).
A hospital emergency room is the everyday model. Patients arrive in one order and are seen in another, by severity. A later patient with a more serious condition goes first, and that reordering is the whole point.
- Min or max is a choice of comparison: a min-priority queue serves the smallest key first
- Extract or peek on an empty priority queue is an error, as with any queue
- Practice: implement max heap, kth largest element in a stream
Why a Heap and Not a List
Every priority queue implementation trades the cost of insert against the cost of extract. The two obvious ones each fail on one operation, and comparing them shows what the heap buys.
An unsorted list makes insert trivial, an append at O(1), but extract must scan every item to find the best, O(n). A sorted list turns this around: extract is O(1) from the end, but insert must find the right place and shift, O(n).
Either is fine when one operation is far more common. When both are frequent, both are slow, and a binary heap gives O(log n) for each.
A heap is a complete binary tree in which every parent is at least as good as its children (no larger, in a min-heap). The order is partial: it compares parent with child only and says nothing about siblings. That looseness is why updates are cheap: fixing one root-to-leaf path is enough, where keeping a total order would cost far more.
Insert appends at the end and sifts up while the new item beats its parent. Extract takes the root, moves the last item into its place and sifts down, swapping with the better of the two children until neither child is better. Each touches one path, hence O(log n). The tracer below runs both on five values.
Because the tree is complete it needs no pointers: stored in an array, the children of index i are at 2i + 1 and 2i + 2 and the parent at ⌊(i − 1) / 2⌋. The data sits in one block of memory, which is friendly to the CPU cache, so heaps are fast in practice as well as on paper.
Other heaps serve special needs. A binomial heap merges two heaps in O(log n). A Fibonacci heap has O(1) amortised insert and decrease-key, which improves Dijkstra's bound to O(E + V log V), though its constant factors are large enough that binary heaps usually win in practice. A d-ary heap gives each node d children, making decrease-key cheaper and extract dearer.
| Backing | Insert | Extract | Peek |
|---|---|---|---|
| Unsorted list | O(1) | O(n) | O(n) |
| Sorted list | O(n) | O(1) | O(1) |
| Binary heap | O(log n) | O(log n) | O(1) |
| Balanced BST | O(log n) | O(log n) | O(log n) |
| Fibonacci heap | O(1) amortised | O(log n) amortised | O(1) |
- The heap array is not sorted; heap sort is what turns it into sorted order, one extract at a time
- A balanced BST also works, and adds ordered iteration and search, at a higher constant cost
- With a small fixed set of priority levels (say 0 to 9), an array of queues gives O(1) insert and extract
Ties, Updates, and the Practical Traps
Three details cause most bugs, and none of them is in the heap algorithm itself.
Ties are not stable. Two items with equal priority come out in an unspecified order, because the heap says nothing about siblings. If arrival order should break ties, make the priority a pair: (priority, counter), with a counter that goes up on every push. Comparison then falls through to the counter and the order becomes predictable.
In Python the counter also prevents a crash. heapq compares whole tuples, so if two priorities tie and the payloads cannot be compared (two dicts, say), it raises a TypeError. With a unique counter in the middle, (priority, counter, item), the comparison never reaches the payload.
Decrease-key needs a position index. Dijkstra's algorithm lowers a vertex's tentative distance, but a heap cannot find that vertex without an O(n) search. There are two answers. Keep a position map from item to array index, updated on every swap, for a true O(log n) decrease-key. Or, much more commonly, push a duplicate with the better priority and skip stale entries when they come out, checking whether the popped distance still matches the best one recorded.
The lazy version is what most real code uses. It can hold up to E entries instead of V, so it costs O(E log E), which is the same as O(E log V) because log E ≤ 2 log V. In return there is no index map to keep in sync, and far less to get wrong.
Max heap from a min heap. Many libraries offer only a min heap. Get a max heap by negating priorities on the way in and out, or by passing a reversed comparator where the library allows one. Negation fails on unsigned types and on the most negative integer, so a comparator is safer when it is available.
Building a heap from n existing items is O(n), not O(n log n). Sifting down from the last internal node back to the root costs less than n inserts, because most nodes are near the bottom where sift-down is short. Use the library's heapify instead of a push loop when the data is already there.
- Equal priorities come out in no fixed order; add a counter if order matters
- Changing an item's priority directly inside the array, without sifting, silently breaks the heap
- Python:
heapq.heapify(list)builds in O(n); C++:std::make_heap; Java:new PriorityQueue<>(collection)
Terms, operations, and practical uses
Core Concepts
- Heap PropertyEvery parent is ordered before or equal to its children: no larger in a min-heap, no smaller in a max-heap.
- Complete Binary TreeA tree where every level is fully populated except possibly the last level, which is filled from left to right.
- Sift-Up / SwimMoving a newly inserted item up, swapping with its parent, until the heap property holds again.
Heap Operations
- Sift-Down / SinkMoving the root item down, swapping with the smaller (or larger) child, until the heap property holds again.
- HeapifyTurning an arbitrary array into a heap in O(n) by sifting down every non-leaf node, from the last one back to the root.
- Extract-MinRemoving and returning the root element of a min-heap, followed by replacing it with the last element and sifting down.
Applications
- Dijkstra's AlgorithmUses a priority queue to always process the nearest unvisited vertex next, guaranteeing the shortest path.
- Huffman CodingRepeatedly extracts the two lowest-frequency trees from a priority queue to build an optimal prefix code tree.
- Kth Largest ElementA min-heap of size k over n items keeps the k largest; its root is the kth largest, in O(n log k) time.
Code in Python, C++ and Java
class PriorityQueue:
def __init__(self):
self.heap = []
def push(self, val):
heap = self.heap
heap.append(val)
i = len(heap) - 1
while i > 0:
parent = (i - 1) // 2
if heap[i] >= heap[parent]:
break
heap[i], heap[parent] = heap[parent], heap[i]
i = parent
def pop(self):
heap = self.heap
val = heap[0]
heap[0] = heap[-1]
heap.pop()
i, n = 0, len(heap)
while True:
l, r, smallest = 2 * i + 1, 2 * i + 2, i
if l < n and heap[l] < heap[smallest]:
smallest = l
if r < n and heap[r] < heap[smallest]:
smallest = r
if smallest == i:
break
heap[i], heap[smallest] = heap[smallest], heap[i]
i = smallest
return val
pq = PriorityQueue()
for value in (10, 5, 1, 8, 3):
pq.push(value)
print('Heap array:', pq.heap)
first = pq.pop()
second = pq.pop()
print(f'Popped {first}, {second}')
print('Heap array:', pq.heap)#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
class PriorityQueue {
public:
vector<int> heap;
void push(int val) {
heap.push_back(val);
int i = heap.size() - 1;
while (i > 0) {
int parent = (i - 1) / 2;
if (heap[i] >= heap[parent]) break;
swap(heap[i], heap[parent]);
i = parent;
}
}
int pop() {
int val = heap.front();
heap.front() = heap.back();
heap.pop_back();
int i = 0, n = heap.size();
while (true) {
int l = 2 * i + 1, r = l + 1, smallest = i;
if (l < n && heap[l] < heap[smallest]) smallest = l;
if (r < n && heap[r] < heap[smallest]) smallest = r;
if (smallest == i) break;
swap(heap[i], heap[smallest]);
i = smallest;
}
return val;
}
};
void print(const vector<int>& heap) {
cout << "Heap array: [";
for (size_t i = 0; i < heap.size(); i++) {
if (i) cout << ", ";
cout << heap[i];
}
cout << "]\n";
}
int main() {
PriorityQueue pq;
for (int value : {10, 5, 1, 8, 3}) pq.push(value);
print(pq.heap);
int first = pq.pop();
int second = pq.pop();
cout << "Popped " << first << ", " << second << "\n";
print(pq.heap);
}import java.util.*;
public class Main {
static class PriorityQueue {
List<Integer> heap = new ArrayList<>();
void push(int val) {
heap.add(val);
int i = heap.size() - 1;
while (i > 0) {
int parent = (i - 1) / 2;
if (heap.get(i) >= heap.get(parent)) break;
Collections.swap(heap, i, parent);
i = parent;
}
}
int pop() {
int val = heap.get(0);
heap.set(0, heap.get(heap.size() - 1));
heap.remove(heap.size() - 1);
int i = 0, n = heap.size();
while (true) {
int l = 2 * i + 1, r = l + 1, smallest = i;
if (l < n && heap.get(l) < heap.get(smallest)) smallest = l;
if (r < n && heap.get(r) < heap.get(smallest)) smallest = r;
if (smallest == i) break;
Collections.swap(heap, i, smallest);
i = smallest;
}
return val;
}
}
public static void main(String[] args) {
PriorityQueue pq = new PriorityQueue();
for (int value : new int[]{10, 5, 1, 8, 3}) pq.push(value);
System.out.println("Heap array: " + pq.heap);
int first = pq.pop();
int second = pq.pop();
System.out.println("Popped " + first + ", " + second);
System.out.println("Heap array: " + pq.heap);
}
}Step through it
Running on insert 10, 5, 1, 8, 3; peek; extract-min twice
Where It Is Used, and the Library Forms
Dijkstra's algorithm is the standard application: repeatedly extract the unvisited vertex with the smallest tentative distance. Without a priority queue, finding that vertex is a linear scan and the algorithm is O(V²). A* search is the same loop with priority equal to cost so far plus a heuristic estimate.
Merging k sorted lists puts the head of each list in a heap of size k, then repeatedly extracts the smallest and pushes the next item from the same list. That is O(N log k) instead of O(N·k) for repeated scans, and it is the merge step of external sorting. Practice: merge k sorted lists.
Top-k problems keep a heap of fixed size k, with a twist: to find the k largest items, keep a min heap of size k. Each new item is compared with the smallest one kept; if it is larger, it replaces it. That is O(n log k) time and O(k) space, better than sorting when k is small next to n. Practice: kth largest element in an array, top k frequent elements.
Scheduling is the operating-system case: a run queue ordered by process priority (see priority scheduling). Event simulation orders pending events by time. Huffman coding repeatedly extracts the two least frequent symbols to build its tree.
The libraries differ in one important way. Python has heapq, which works on a plain list instead of wrapping it in a class, and is a min heap only. C++ has std::priority_queue, a max heap by default, reversed with std::greater; make_heap, push_heap and pop_heap are also available on any container. Java has PriorityQueue, a min heap by default, which takes a Comparator for any other order.
The default differs between C++ and the other two, which regularly flips results when code is ported between them.
- A running median uses two heaps, a max heap for the lower half and a min heap for the upper: find median from data stream
- k closest points is top-k with distance as the priority: k closest points
- If items never leave in priority order, a plain queue or a sorted array is simpler