Imagine a hospital emergency room. Patients don’t get seen in the order they arrived — they get seen based on the severity of their condition. A patient with a heart attack jumps ahead of someone with a sprained ankle, regardless of who checked in first. That’s exactly the problem a priority queue solves in software.
In this post, we’ll cover what priority queues are, how the binary heap makes them efficient, and how the core operations — insertion, extraction, and heapify — actually work.
What Is a Priority Queue?
A priority queue is a specialized version of a regular queue. Instead of dequeuing elements in the order they arrived (FIFO), it always dequeues the element with the highest priority first.
Priority can be defined as:
- Max-priority queue — the largest value is always at the front
- Min-priority queue — the smallest value is always at the front
Real-World Use Cases
| Use Case | Priority Rule |
|---|---|
| OS job scheduler | Higher priority tasks run first |
| Dijkstra’s shortest path | Always process the closest unvisited node |
| Hospital triage system | Most critical patients seen first |
| Event simulation | Process earliest-timestamp events first |
Priority queues are most commonly implemented using a binary heap stored in an array — which gives O(log n) for both insertion and extraction, much better than the O(n) you’d get with a sorted array or linked list.
What Is a Binary Heap?
A binary heap is a complete binary tree that satisfies the heap property:
- Max-heap: Every node’s value is greater than or equal to its children’s values. The maximum is always at the root.
- Min-heap: Every node’s value is less than or equal to its children’s values. The minimum is always at the root.
“Complete binary tree” means all levels are fully filled except possibly the last, which fills from left to right. This shape is what makes the array representation work so cleanly.
Max-heap example:
50
/ \
31 40
/ \ /
14 10 23
Every parent is larger than its children. The root (50) is always the maximum.
Time Complexity
| Operation | Complexity |
|---|---|
| Push (insert) | O(log n) |
| Pop (extract top) | O(log n) |
| Peek (read top) | O(1) |
| Heapify (build from array) | O(n) |
Storing a Heap in an Array
The elegance of a binary heap is that you don’t need pointers or a node struct — the entire tree fits neatly into a flat array. The parent-child relationships are computed mathematically from the index.
0-based indexing (most common in code):
A[0]
/ \
A[1] A[2]
/ \ / \
A[3] A[4] A[5] A[6]
| Relationship | Formula |
|---|---|
| Parent of i | (i - 1) / 2 |
| Left child of i | 2 * i + 1 |
| Right child of i | 2 * i + 2 |
So for the max-heap [50, 31, 40, 14, 10, 23]:
- Node at index 2 (value 40): parent is index
(2-1)/2 = 0(value 50) ✓ - Node at index 2 (value 40): left child is index
2*2+1 = 5(value 23) ✓
No pointers needed — just arithmetic.
Operation 1: Push (Insertion)
Inserting into a heap always follows the same two-step pattern:
- Add the new element at the end of the array (to keep the tree complete)
- Bubble up — swap with the parent repeatedly until the heap property is restored
Step-by-Step Example (Max-heap)
Starting heap: [50, 31, 23, 14, 10] — inserting 40
Step 1: Append 40 to the end
Array: [50, 31, 23, 14, 10, 40]
40 is at index 5
Step 2: Bubble up — compare with parent
Parent of index 5 = (5-1)/2 = index 2 → value 23
40 > 23 → swap!
Array: [50, 31, 40, 14, 10, 23]
Step 3: Continue bubbling up from index 2
Parent of index 2 = (2-1)/2 = index 0 → value 50
40 < 50 → heap property satisfied, stop ✓
Final: [50, 31, 40, 14, 10, 23]
As a tree:
50
/ \
31 40 ← 40 bubbled up from the bottom
/ \ /
14 10 23
Complexity: O(log n) — in the worst case, the new element bubbles all the way from the bottom to the root, traversing the height of the tree.
Operation 2: Pop (Extract Top)
Popping always removes the root (the max in a max-heap, min in a min-heap). But you can’t just delete the root — the tree would fall apart. The trick is a three-step process:
- Swap the root with the last element in the array
- Remove the last element (which is now the old root — this is your return value)
- Bubble down from the root — swap with the larger child until the heap property is restored
Step-by-Step Example (Max-heap)
Starting heap: [50, 31, 40, 14, 10, 23] — extracting the max (50)
Step 1: Swap root (50) with last element (23)
Array: [23, 31, 40, 14, 10, 50]
Step 2: Remove last element (50) — this is returned
Array: [23, 31, 40, 14, 10]
Step 3: Bubble down from root (index 0, value 23)
Children: left = index 1 (31), right = index 2 (40)
Largest child is 40 at index 2
23 < 40 → swap!
Array: [40, 31, 23, 14, 10]
Step 4: Continue from index 2 (value 23)
Children: left = index 5, right = index 6 → both out of bounds
No children — stop ✓
Final: [40, 31, 23, 14, 10]
As a tree:
40 ← new max at root
/ \
31 23
/ \
14 10
Complexity: O(log n) — the swapped element bubbles down at most the height of the tree.
Operation 3: Heapify (Build a Heap from an Array)
What if you have an unsorted array and want to turn it into a heap? You could push each element one by one — but that costs O(n log n). The heapify (or buildHeap) algorithm does it in O(n).
The key insight: leaf nodes (the bottom half of the array) are already valid heaps by themselves — they have no children to violate the heap property. So we only need to bubble down from the non-leaf nodes, working backwards from the last parent to the root.
python
def heapify(arr, i, n):
left = 2 * i + 1
right = 2 * i + 2
largest = i # assume current node is largest
# check if left child exists and is greater
if left < n and arr[left] > arr[largest]:
largest = left
# check if right child exists and is greater
if right < n and arr[right] > arr[largest]:
largest = right
# if current node is not the largest, swap and recurse
if largest != i:
arr[i], arr[largest] = arr[largest], arr[i]
heapify(arr, largest, n)
def buildMaxHeap(arr, n):
# start from the last non-leaf node, work up to root
i = n // 2
while i >= 0:
heapify(arr, i, n)
i -= 1
n // 2 gives you the index of the last parent node. Everything after that index is a leaf. By calling heapify on each parent from bottom to top, we guarantee every subtree satisfies the heap property by the time we process its parent.
Complexity: O(n) — counterintuitively, this is faster than pushing elements one by one (O(n log n)), because most of the work happens near the bottom of the tree where the subtrees are small.
Min-heap vs. Max-heap: Which to Use?
| Max-heap | Min-heap | |
|---|---|---|
| Root holds | Largest value | Smallest value |
| Use when you need | Quickly access the maximum | Quickly access the minimum |
| Example | Find the k largest elements | Dijkstra’s algorithm |
| In Python | heapq (negate values for max) | heapq (default) |
| In C++ | priority_queue<int> (default) | priority_queue<int, vector<int>, greater<int>> |
| In Java | PriorityQueue (default min) | PriorityQueue (default) |
Using Priority Queues in Practice
You almost never implement a binary heap from scratch. Every major language has one built in:
Python:
python
import heapq
# Min-heap (default)
heap = []
heapq.heappush(heap, 10)
heapq.heappush(heap, 5)
heapq.heappush(heap, 20)
print(heapq.heappop(heap)) # 5 — smallest first
# Max-heap: negate values
heapq.heappush(heap, -10)
print(-heapq.heappop(heap)) # 10 — largest first
C++:
cpp
#include <queue>
// Max-heap (default)
priority_queue<int> maxHeap;
maxHeap.push(10);
maxHeap.push(5);
maxHeap.push(20);
cout << maxHeap.top(); // 20
maxHeap.pop();
// Min-heap
priority_queue<int, vector<int>, greater<int>> minHeap;
minHeap.push(10);
cout << minHeap.top(); // smallest value
Summary
Priority queues are essential for any problem where you need to repeatedly access the “most important” element:
- A priority queue dequeues by priority, not by arrival order
- The binary heap is the standard implementation — a complete binary tree stored in a flat array
- Parent-child relationships are computed with simple index math: left =
2i+1, right =2i+2, parent =(i-1)/2 - Push appends to the end and bubbles up: O(log n)
- Pop swaps root with last element, removes it, then bubbles down: O(log n)
- BuildHeap converts an unsorted array to a heap in O(n) by bubbling down from the last parent to the root
- Peek at the top element is always O(1)
Once you understand the heap, algorithms like Dijkstra’s shortest path and Kruskal’s MST — both of which rely on a priority queue — become much clearer.