Programming Search⌘K

Conceptcore

Priority queue

Also called priority queue, heap queue, min-heap, max-heap, PriorityQueue, heapq, BinaryHeap, std::priority_queue, container/heap.

A priority queue gives back the item with the best priority first, not the oldest item. Libraries build it on a binary heap, so a push or a pop takes logarithmic time.

Applies to
core-languages

Idea

A plain queue serves items in the order they arrive. A priority queue serves the most important item first. Wikipedia: "a priority queue is an abstract data type similar to a regular queue where each element has an associated priority determining its order of service."1 A hospital that treats the worst injury first, a scheduler that runs the most urgent task first, and a search that expands the cheapest path first all use one.

import heapq

tasks = []
heapq.heappush(tasks, (3, "update docs"))
heapq.heappush(tasks, (1, "fix outage"))
heapq.heappush(tasks, (2, "review patch"))
heapq.heappush(tasks, (1, "call customer"))

while tasks:
    priority, name = heapq.heappop(tasks)
    print(priority, name)
Output
1 call customer
1 fix outage
2 review patch
3 update docs

The two tasks with priority 1 come out in the order of their names, because Python compares the tuples item by item. The Pitfalls section shows why that can fail.

How it works

Operations. A priority queue has three main operations: insert an item with a priority, remove the item with the best priority, and peek at that item.1 In a min-priority queue the best item has the smallest value, and in a max-priority queue it has the largest. Wikipedia notes that "higher priority can be given either to the lesser or to the greater values".1

The binary heap. Wikipedia: "To improve performance, priority queues are typically based on a heap". A heap gives logarithmic time for an insert and a removal, and linear time to build the heap from n items.1 A binary heap is a complete binary tree stored in an array. In a min-heap, each parent is less than or equal to its children, so the smallest item is at index 0. The Python documentation states the rule as heap[k] <= heap[2*k+1] and heap[k] <= heap[2*k+2].2

  • An insert puts the new item at the end of the array and moves it up while it is smaller than its parent.
  • A removal takes the item at index 0, moves the last item to index 0, and moves that item down while a child is smaller.

How heaps work in detail is on the algorithm site: binary heap.

A priority queue is not a sorted list. Only the first item is in its final place. Wikipedia: "While priority queues are often implemented using heaps, they are conceptually distinct."1 The rest of the array is in heap order, which is not sorted order.

In languages

LanguageVerdictNote
PythonStandard library
C++Standard library
JavaStandard library
CIdiom
C#Standard library
JavaScriptIdiom
TypeScriptIdiomTypeScript has no priority queue type. A program writes a binary heap over an array, as in the JavaScript example. No example file exists.
GoStandard library
RustStandard library
KotlinStandard libraryKotlin on the JVM uses java.util.PriorityQueue with a comparator. No example file exists because kotlinc is not installed.
SQLIdiomA table with a priority column and an index works as a queue. ORDER BY priority with LIMIT 1 selects the next row.
BashDoes not applyBash has no priority queue. A script can sort lines with sort -n, but that is not a queue.
PowerShellStandard library[System.Collections.Generic.PriorityQueue[TElement,TPriority]] from .NET dequeues the lowest priority first. No example file exists because pwsh is not installed.
HTMLDoes not applyHTML is markup. It has no data structures for a program.
CSSDoes not applyCSS style rules have no data structures.
Regular expressionsDoes not applyA regular expression matches text. It has no data structures.
Language Verdict Form
Python stdlib heapq functions on a plain list, smallest first2
JavaScript idiom no built-in type; a hand-written binary heap
TypeScript idiom as JavaScript
Java stdlib PriorityQueue, smallest first3
C idiom a hand-written heap in an array
C++ stdlib std::priority_queue, largest first4
C# stdlib PriorityQueue<TElement, TPriority>, smallest priority first5
Go stdlib container/heap over a type that implements heap.Interface6
Rust stdlib BinaryHeap, largest first7
Kotlin stdlib java.util.PriorityQueue on the JVM
PowerShell stdlib [System.Collections.Generic.PriorityQueue[TElement,TPriority]] from .NET
Bash n/a no priority queue; sort -n sorts lines once
SQL idiom ORDER BY priority with LIMIT 1 over an indexed table
Regex n/a a pattern has no data structures
HTML/CSS n/a markup and style rules have no data structures

Python. heapq works on a list. "The interesting property of a min-heap is that its smallest element is always the root".2 That is heap[0]. Python 3.14 added max-heap functions such as heappush_max and heappop_max.2 On older versions, a program pushes negated numbers or wraps the items.

Java. PriorityQueue is "An unbounded priority queue based on a priority heap."3 "The head of this queue is the least element with respect to the specified ordering."3 The items are ordered "by a Comparator provided at queue construction time" if the program gives one.3 A reversed comparator gives a max-heap.

C++. std::priority_queue "is a container adaptor that provides constant time lookup of the largest (by default) element, at the expense of logarithmic insertion and extraction".4 For a min-heap, "using std::greater would cause the smallest element to appear as the top()".4

C#. PriorityQueue<TElement, TPriority> "Represents a collection of items that have a value and a priority. On dequeue, the item with the lowest priority value is removed."5 It "Implements an array-backed, quaternary min-heap."5 The element and the priority are separate, so the element type does not need an order.

Rust. BinaryHeap is "A priority queue implemented with a binary heap. This will be a max-heap."7 "Either core::cmp::Reverse or a custom Ord implementation can be used to make BinaryHeap a min-heap."7

Go. "Package heap provides heap operations for any type that implements heap.Interface."6 The program writes Len, Less, Swap, Push and Pop for its own slice type. "A heap is a common way to implement a priority queue."6

The example files push four tasks with priorities, pop them in priority order, and show how to get the other order.

PythonGitHub
import heapq

tasks = []
for priority, name in [(3, "update docs"), (1, "fix outage"), (2, "review patch"), (4, "plan sprint")]:
    heapq.heappush(tasks, (priority, name))

print("peek:", tasks[0][1])
while tasks:
    priority, name = heapq.heappop(tasks)
    print(priority, name)

max_heap = [-n for n in [3, 1, 2, 4]]
heapq.heapify(max_heap)
order = []
while max_heap:
    order.append(-heapq.heappop(max_heap))
print("largest first:", *order)
Output
peek: fix outage
1 fix outage
2 review patch
3 update docs
4 plan sprint
largest first: 4 3 2 1
  • Verdict: stdlib. heapq keeps a plain list in min-heap order. heappush and heappop take logarithmic time, and tasks[0] is the smallest item.
  • A tuple sorts by its first item, so (priority, name) puts the lowest priority first.
  • This example negates the numbers for a max-heap, because the max-heap functions need Python 3.14.
#include <functional>
#include <iostream>
#include <queue>
#include <string>
#include <utility>
#include <vector>

int main() {
    using Task = std::pair<int, std::string>;
    std::priority_queue<Task, std::vector<Task>, std::greater<Task>> tasks;
    tasks.push({3, "update docs"});
    tasks.push({1, "fix outage"});
    tasks.push({2, "review patch"});
    tasks.push({4, "plan sprint"});

    std::cout << "peek: " << tasks.top().second << '\n';
    while (!tasks.empty()) {
        std::cout << tasks.top().first << ' ' << tasks.top().second << '\n';
        tasks.pop();
    }

    std::priority_queue<int> max_heap;
    for (int n : {3, 1, 2, 4}) {
        max_heap.push(n);
    }
    std::cout << "largest first:";
    while (!max_heap.empty()) {
        std::cout << ' ' << max_heap.top();
        max_heap.pop();
    }
    std::cout << '\n';
}
Output
peek: fix outage
1 fix outage
2 review patch
3 update docs
4 plan sprint
largest first: 4 3 2 1
  • Verdict: stdlib. std::priority_queue gives the largest item first. With std::greater, it gives the smallest first.
  • top reads the best item and pop removes it. pop returns nothing.
JavaGitHub
import java.util.Comparator;
import java.util.List;
import java.util.PriorityQueue;

public class Main {
    record Task(int priority, String name) {}

    public static void main(String[] args) {
        PriorityQueue<Task> tasks = new PriorityQueue<>(Comparator.comparingInt(Task::priority));
        tasks.add(new Task(3, "update docs"));
        tasks.add(new Task(1, "fix outage"));
        tasks.add(new Task(2, "review patch"));
        tasks.add(new Task(4, "plan sprint"));

        System.out.println("peek: " + tasks.peek().name());
        while (!tasks.isEmpty()) {
            Task task = tasks.poll();
            System.out.println(task.priority() + " " + task.name());
        }

        PriorityQueue<Integer> maxHeap = new PriorityQueue<>(Comparator.reverseOrder());
        maxHeap.addAll(List.of(3, 1, 2, 4));
        StringBuilder order = new StringBuilder();
        while (!maxHeap.isEmpty()) {
            order.append(" ").append(maxHeap.poll());
        }
        System.out.println("largest first:" + order);
    }
}
Output
peek: fix outage
1 fix outage
2 review patch
3 update docs
4 plan sprint
largest first: 4 3 2 1
  • Verdict: stdlib. PriorityQueue with a Comparator orders the records by priority. peek reads the head and poll removes it.
  • Comparator.reverseOrder() makes a max-heap.
#include <stdbool.h>
#include <stdio.h>

#define CAPACITY 8

struct task {
    int priority;
    const char *name;
};

struct heap {
    struct task items[CAPACITY];
    int count;
    bool (*before)(const struct task *, const struct task *);
};

static bool lower_first(const struct task *a, const struct task *b) {
    return a->priority < b->priority;
}

static bool higher_first(const struct task *a, const struct task *b) {
    return a->priority > b->priority;
}

static void swap(struct task *a, struct task *b) {
    struct task t = *a;
    *a = *b;
    *b = t;
}

static bool push(struct heap *h, struct task t) {
    if (h->count == CAPACITY) {
        return false;
    }
    int i = h->count++;
    h->items[i] = t;
    while (i > 0) {
        int parent = (i - 1) / 2;
        if (!h->before(&h->items[i], &h->items[parent])) {
            break;
        }
        swap(&h->items[i], &h->items[parent]);
        i = parent;
    }
    return true;
}

static bool pop(struct heap *h, struct task *out) {
    if (h->count == 0) {
        return false;
    }
    *out = h->items[0];
    h->count--;
    h->items[0] = h->items[h->count];
    int i = 0;
    for (;;) {
        int left = 2 * i + 1;
        int right = left + 1;
        int best = i;
        if (left < h->count && h->before(&h->items[left], &h->items[best])) {
            best = left;
        }
        if (right < h->count && h->before(&h->items[right], &h->items[best])) {
            best = right;
        }
        if (best == i) {
            break;
        }
        swap(&h->items[i], &h->items[best]);
        i = best;
    }
    return true;
}

int main(void) {
    struct task input[] = {{3, "update docs"}, {1, "fix outage"}, {2, "review patch"}, {4, "plan sprint"}};
    int n = (int)(sizeof input / sizeof input[0]);
    struct task t = {0, ""};

    struct heap tasks = {.count = 0, .before = lower_first};
    for (int i = 0; i < n; i++) {
        push(&tasks, input[i]);
    }
    printf("peek: %s\n", tasks.items[0].name);
    while (pop(&tasks, &t)) {
        printf("%d %s\n", t.priority, t.name);
    }

    struct heap max_heap = {.count = 0, .before = higher_first};
    for (int i = 0; i < n; i++) {
        push(&max_heap, input[i]);
    }
    printf("largest first:");
    while (pop(&max_heap, &t)) {
        printf(" %d", t.priority);
    }
    printf("\n");
    return 0;
}
Output
peek: fix outage
1 fix outage
2 review patch
3 update docs
4 plan sprint
largest first: 4 3 2 1
  • Verdict: idiom. C has no priority queue type. A fixed array, a count and a comparison function make a bounded binary heap.
  • push returns false when the array is full, and pop returns false when the heap is empty.
  • The same code gives a max-heap with the higher_first function.
var tasks = new PriorityQueue<string, int>();
tasks.Enqueue("update docs", 3);
tasks.Enqueue("fix outage", 1);
tasks.Enqueue("review patch", 2);
tasks.Enqueue("plan sprint", 4);

Console.WriteLine("peek: " + tasks.Peek());
while (tasks.TryDequeue(out string? name, out int priority))
{
    Console.WriteLine(priority + " " + name);
}

var maxHeap = new PriorityQueue<int, int>(Comparer<int>.Create((a, b) => b.CompareTo(a)));
foreach (int n in new[] { 3, 1, 2, 4 })
{
    maxHeap.Enqueue(n, n);
}
var order = new List<int>();
while (maxHeap.Count > 0)
{
    order.Add(maxHeap.Dequeue());
}
Console.WriteLine("largest first: " + string.Join(" ", order));
Output
peek: fix outage
1 fix outage
2 review patch
3 update docs
4 plan sprint
largest first: 4 3 2 1
  • Verdict: stdlib. PriorityQueue<TElement, TPriority> stores each element with a separate priority and dequeues the lowest priority first.
  • TryDequeue returns false when the queue is empty.
  • A reversed Comparer makes a max-heap.
JavaScriptGitHub
class PriorityQueue {
  #items = [];
  #before;

  constructor(before) {
    this.#before = before;
  }

  get size() {
    return this.#items.length;
  }

  peek() {
    return this.#items[0];
  }

  push(item) {
    const items = this.#items;
    items.push(item);
    let i = items.length - 1;
    while (i > 0) {
      const parent = (i - 1) >> 1;
      if (!this.#before(items[i], items[parent])) break;
      [items[i], items[parent]] = [items[parent], items[i]];
      i = parent;
    }
  }

  pop() {
    const items = this.#items;
    const top = items[0];
    const last = items.pop();
    if (items.length > 0) {
      items[0] = last;
      let i = 0;
      for (;;) {
        const left = 2 * i + 1;
        const right = left + 1;
        let best = i;
        if (left < items.length && this.#before(items[left], items[best])) best = left;
        if (right < items.length && this.#before(items[right], items[best])) best = right;
        if (best === i) break;
        [items[i], items[best]] = [items[best], items[i]];
        i = best;
      }
    }
    return top;
  }
}

const tasks = new PriorityQueue((a, b) => a.priority < b.priority);
const input = [[3, "update docs"], [1, "fix outage"], [2, "review patch"], [4, "plan sprint"]];
for (const [priority, name] of input) {
  tasks.push({ priority, name });
}

console.log("peek:", tasks.peek().name);
while (tasks.size > 0) {
  const { priority, name } = tasks.pop();
  console.log(priority, name);
}

const maxHeap = new PriorityQueue((a, b) => a > b);
for (const n of [3, 1, 2, 4]) maxHeap.push(n);
const order = [];
while (maxHeap.size > 0) order.push(maxHeap.pop());
console.log("largest first:", order.join(" "));
Output
peek: fix outage
1 fix outage
2 review patch
3 update docs
4 plan sprint
largest first: 4 3 2 1
  • Verdict: idiom. JavaScript has no priority queue type. This class keeps a binary heap in an array, with a before function that decides the order.
  • push moves the new item up, and pop moves the last item down from the root.
  • The same class gives a max-heap when before uses >.
package main

import (
	"container/heap"
	"fmt"
)

type task struct {
	priority int
	name     string
}

// taskHeap is a min-heap of tasks, ordered by priority.
type taskHeap []task

func (h taskHeap) Len() int {
	return len(h)
}

func (h taskHeap) Less(i, j int) bool {
	return h[i].priority < h[j].priority
}

func (h taskHeap) Swap(i, j int) {
	h[i], h[j] = h[j], h[i]
}

func (h *taskHeap) Push(x any) {
	*h = append(*h, x.(task))
}

func (h *taskHeap) Pop() any {
	old := *h
	n := len(old)
	item := old[n-1]
	*h = old[:n-1]
	return item
}

// maxInts is a max-heap, because Less uses >.
type maxInts []int

func (h maxInts) Len() int {
	return len(h)
}

func (h maxInts) Less(i, j int) bool {
	return h[i] > h[j]
}

func (h maxInts) Swap(i, j int) {
	h[i], h[j] = h[j], h[i]
}

func (h *maxInts) Push(x any) {
	*h = append(*h, x.(int))
}

func (h *maxInts) Pop() any {
	old := *h
	n := len(old)
	item := old[n-1]
	*h = old[:n-1]
	return item
}

func main() {
	tasks := &taskHeap{}
	input := []task{{3, "update docs"}, {1, "fix outage"}, {2, "review patch"}, {4, "plan sprint"}}
	for _, t := range input {
		heap.Push(tasks, t)
	}

	fmt.Println("peek:", (*tasks)[0].name)
	for tasks.Len() > 0 {
		t := heap.Pop(tasks).(task)
		fmt.Println(t.priority, t.name)
	}

	numbers := &maxInts{3, 1, 2, 4}
	heap.Init(numbers)
	fmt.Print("largest first:")
	for numbers.Len() > 0 {
		fmt.Print(" ", heap.Pop(numbers))
	}
	fmt.Println()
}
Output
peek: fix outage
1 fix outage
2 review patch
3 update docs
4 plan sprint
largest first: 4 3 2 1
  • Verdict: stdlib. container/heap works on any type with Len, Less, Swap, Push and Pop. The program calls heap.Push and heap.Pop, not the methods directly.
  • Less decides the order. With >, the heap gives the largest item first.
RustGitHub
use std::cmp::Reverse;
use std::collections::BinaryHeap;

fn main() {
    let input = [
        (3, "update docs"),
        (1, "fix outage"),
        (2, "review patch"),
        (4, "plan sprint"),
    ];
    let mut tasks = BinaryHeap::new();
    for (priority, name) in input {
        tasks.push(Reverse((priority, name)));
    }

    if let Some(Reverse((_, name))) = tasks.peek() {
        println!("peek: {name}");
    }
    while let Some(Reverse((priority, name))) = tasks.pop() {
        println!("{priority} {name}");
    }

    let mut max_heap = BinaryHeap::from([3, 1, 2, 4]);
    let mut order = Vec::new();
    while let Some(n) = max_heap.pop() {
        order.push(n.to_string());
    }
    println!("largest first: {}", order.join(" "));
}
Output
peek: fix outage
1 fix outage
2 review patch
3 update docs
4 plan sprint
largest first: 4 3 2 1
  • Verdict: stdlib. BinaryHeap gives the largest item first. Reverse turns it into a min-heap.
  • peek returns an Option with a reference, and pop returns an Option with the item.
  • Min and max. The same structure with the opposite comparison. See comparator.
  • Indexed priority queue. A priority queue that can change the priority of an item that is already in it. Wikipedia notes that Dijkstra's algorithm needs "the ability to alter the priority of a particular vertex in the priority queue efficiently".1 Most standard libraries do not offer this. The heapq documentation suggests to "mark the entry as removed and add a new entry with the revised priority".2
  • Bounded top-k. A heap of size k keeps the k largest items of a stream: push each item, and pop the smallest when the heap has more than k items. Python has heapq.nlargest and heapq.nsmallest for this.2
  • Concurrent priority queues. Java has PriorityBlockingQueue for threads.3
  • Priority queues between services. See priority-queue-pattern.

Pitfalls

Equal priorities are not served first in, first out

A binary heap does not keep the arrival order of items with equal priority. Wikipedia: "In other implementations, the order of elements with the same priority is undefined."1 Java says that "ties are broken arbitrarily".3 The .NET type "does not guarantee first-in-first-out semantics for elements of equal priority".5

In Python, a tie also compares the second item of the tuple. If that item cannot be compared, the push fails.

This code runs but gives a wrong answer on purpose.

import heapq

tasks = []
heapq.heappush(tasks, (1, {"name": "fix outage"}))
try:
    heapq.heappush(tasks, (1, {"name": "call customer"}))
except TypeError as error:
    print("TypeError:", error)
Output
TypeError: '<' not supported between instances of 'dict' and 'dict'

The fix is a counter as the second item. The heapq documentation stores "the priority, an entry count, and the task". "The entry count serves as a tie-breaker so that two tasks with the same priority are returned in the order they were added."2

import heapq
from itertools import count

tasks = []
order = count()
for priority, name in [(1, "fix outage"), (2, "review patch"), (1, "call customer")]:
    heapq.heappush(tasks, (priority, next(order), {"name": name}))

while tasks:
    priority, _, task = heapq.heappop(tasks)
    print(priority, task["name"])
Output
1 fix outage
1 call customer
2 review patch

Printing or iterating a priority queue does not give sorted order

The array of a heap is in heap order. Java warns that the iterator is "not guaranteed to traverse the elements of the priority queue in any particular order".3 Only repeated poll calls give sorted order.

This code runs but gives a wrong answer on purpose.

import java.util.List;
import java.util.PriorityQueue;

public class Main {
    public static void main(String[] args) {
        PriorityQueue<Integer> queue = new PriorityQueue<>();
        for (int n : List.of(5, 1, 4, 2, 3)) {
            queue.add(n);
        }
        System.out.println("printed " + queue);

        StringBuilder polled = new StringBuilder();
        while (!queue.isEmpty()) {
            polled.append(polled.isEmpty() ? "" : " ").append(queue.poll());
        }
        System.out.println("polled " + polled);
    }
}
Output
printed [1, 2, 4, 5, 3]
polled 1 2 3 4 5

The default order differs between languages

std::priority_queue and Rust's BinaryHeap give the largest item first.47 Python, Java and C# give the smallest first.235 Code that is ported between these languages must change the comparison, or it serves the items in reverse.

A changed item breaks the heap

The heap places an item when it is pushed. If the program later changes a field that the comparison uses, the item stays where it is, and the heap order is wrong. Rust says that "It is a logic error for an item to be modified" in this way.7 To change a priority, remove the item and push it again, or push a new entry and skip the old one when it comes out.

Cost

Operation Binary heap Sorted array Unsorted array
insert logarithmic linear constant
remove the best logarithmic constant linear
peek at the best constant constant linear
build from n items linear

The heap figures come from Wikipedia and the library documents. Wikipedia gives the figures for the two naive arrays.1

Java's implementation note gives the same figures: "O(log(n)) time for the enqueuing and dequeuing methods", "linear time for the remove(Object) and contains(Object) methods", and "constant time for the retrieval methods".3 Rust gives the cost of push as O(1) and calls it "an expected cost".7

History

The C++ standard of 1998 "specifies std::priority_queue as one of the STL container adaptor class templates".1 Java added PriorityQueue in version 1.5.3 Python 3.14 added max-heap functions to heapq.2

References

  1. Priority queue, Wikipedia, the introduction; Operations; Implementation; Libraries; Applications
  2. heapq, Heap queue algorithm, Python documentation, the introduction; max-heap functions; Priority Queue Implementation Notes
  3. PriorityQueue (Java SE 27 and JDK 27), the class description; Implementation note
  4. std::priority_queue, cppreference.com, the introduction
  5. PriorityQueue<TElement,TPriority> Class, .NET API reference, the summary; Remarks
  6. heap package, container/heap, Go standard library, Overview; Example (PriorityQueue)
  7. Struct BinaryHeap, The Rust Standard Library, the description; Min-heap; Time complexity

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW4 complete
  • a review of the text: no review record reviews/YSDZN3/text.yaml