AlgoTales · Roadmap

Priority queues

Intermediate · 9 min · code in PHP, JavaScript, Java and Go

Where you will meet this in real life

A priority queue hands you the most important item next, not the one that arrived first. It is usually built on a heap, and it is how apps decide who or what goes first when everything cannot go at once.

Practical use cases

  • Web app: Running urgent jobs first in a queue. A Laravel-style job queue sends welcome emails, invoices and password resets. Without priorities, a bulk newsletter of 50,000 emails makes a password reset wait for an hour. Marking resets as high priority makes the worker pick them first, so the reset email arrives in seconds.
  • Web app: Clinic booking with emergencies first. A hospital app lists waiting patients, and an emergency must be seen before someone with a routine check even if they arrived later. A priority queue ranks patients by seriousness and then arrival time. The doctor screen always shows who is next.
  • System: OS schedulers and route finding. Operating systems choose which program runs next with priorities. Navigation algorithms like Dijkstra and A-star always expand the most promising place first, using a priority queue to keep that choice quick. Without it, every single step would have to scan all the candidates.

The story: The Clinic That Did Not Run First-Come First-Served

Mira went with Grandpa Bhaskar to Dr. Meena's clinic one busy Sunday. A boy with a sprained ankle had arrived first, then a lady for a routine check-up, then a child with a high fever. And then Grandpa clutched his chest.

A normal queue, like the line at the railway ticket window, works first come, first served. Grandpa would have waited for the sprain and the check-up! But the nurse said, "Grandpa Bhaskar, please come in right away." Mira was relieved, and curious. "Nurse, you do not use the arrival order?"

"Not here," smiled the nurse. "Each patient gets a priority number. The most urgent is always next, no matter when they arrived. We call it a priority queue." Then she added, "If two patients are equally urgent, we serve the one who came first." That tie-break rule is important to remember.

Behind the scenes a priority queue is usually built on a heap. Enqueue is a heap insert (climb up), dequeue is an extract (sink down). Both cost about log n steps, even for a thousand patients.

How to spot this problem, and where you need it

First come, first served is not good enough: some items are more urgent or valuable, and they must be handled first even if they arrived later.

Signs you need it

  • Customers complain that an important action, like a password reset or payment confirmation, is stuck behind a bulk task.
  • You keep sorting the waiting list by priority after each new arrival.
  • The task says "process the highest priority first", "always pick the cheapest/closest next" or "triage".

Where to use it in a project

  • Background job systems and notification queues with urgent and bulk work mixed together.
  • Support, triage and dispatch screens that must always show the most important waiting item.

The solution

Give each item a priority number (and, for ties, an arrival number). Store them in a heap, where the best priority is always on top. To add work, insert it. To serve, take the top. Both actions take only a few steps even when thousands of items are waiting, and the order is always right.

Payoff: Before: a password reset waits an hour behind 50,000 newsletter emails. After: it is picked next, within seconds.

Explain it like I am 8

It is like a queue at a water tap in a village, but where the thirstiest or the oldest person goes first, not whoever arrived first. A priority queue always hands you the most important item next, and a heap hides underneath to keep the most important one at the top.

How it works, step by step

  1. A priority queue is an idea with two actions: enqueue (add an item with its priority) and dequeue (remove the most important one).
  2. The usual engine is a heap ordered by priority: a min heap if "1 means first", a max heap if "bigger means first".
  3. Enqueue = heap insert: add at the bottom, climb up.
  4. Dequeue = heap extract: take the root, put the last item on top, sink it.
  5. For equal priorities, add a running counter as a second key so that the earlier arrival goes first (fair ties).

The code in four languages

PHP

<?php
// A heap lives in a plain array. Spot i has children at 2*i+1 and 2*i+2.
// before($x, $y) answers: "does x belong closer to the top than y?"  (default = min-heap)
class Heap {
    private array $a = [];
    private $before;
    public function __construct(?callable $before = null) {
        $this->before = $before ?? fn($x, $y) => $x < $y;
    }
    public function size(): int { return count($this->a); }
    public function peek() { return $this->a[0] ?? null; }
    public function push($v): void {             // put it at the bottom, then climb
        $this->a[] = $v;
        $i = count($this->a) - 1;
        while ($i > 0) {
            $p = intdiv($i - 1, 2);
            if (!($this->before)($this->a[$i], $this->a[$p])) break;
            [$this->a[$i], $this->a[$p]] = [$this->a[$p], $this->a[$i]];
            $i = $p;
        }
    }
    public function pop() {                      // take the top, put the last one on top, sink it
        if (count($this->a) === 0) return null;
        $top = $this->a[0];
        $last = array_pop($this->a);
        $n = count($this->a);
        if ($n > 0) {
            $this->a[0] = $last;
            $i = 0;
            while (true) {
                $l = 2 * $i + 1; $r = $l + 1; $best = $i;
                if ($l < $n && ($this->before)($this->a[$l], $this->a[$best])) $best = $l;
                if ($r < $n && ($this->before)($this->a[$r], $this->a[$best])) $best = $r;
                if ($best === $i) break;
                [$this->a[$i], $this->a[$best]] = [$this->a[$best], $this->a[$i]];
                $i = $best;
            }
        }
        return $top;
    }
}

// A priority queue: items with a priority number (smaller = more urgent).
// Each entry is [priority, arrivalNumber, name]; the arrival number breaks ties fairly.
class PriorityQueue {
    private Heap $heap;
    private int $arrivals = 0;
    public function __construct() {
        $this->heap = new Heap(function ($x, $y) {
            return $x[0] !== $y[0] ? $x[0] < $y[0] : $x[1] < $y[1];
        });
    }
    public function enqueue(string $name, int $priority): void {
        $this->heap->push([$priority, $this->arrivals++, $name]);
    }
    public function dequeue(): ?string {
        $top = $this->heap->pop();
        return $top === null ? null : $top[2];
    }
}

$clinic = new PriorityQueue();
$clinic->enqueue('sprain', 4);
$clinic->enqueue('check-up', 5);
$clinic->enqueue('fever', 2);
$clinic->enqueue('cut', 2);               // same urgency as fever, arrived later
$clinic->enqueue('chest pain', 1);
while (($next = $clinic->dequeue()) !== null) echo $next, PHP_EOL;
// chest pain, fever, cut, sprain, check-up

JavaScript

// A heap lives in a plain array. Spot i has children at 2*i+1 and 2*i+2.
// before(x, y) answers: "does x belong closer to the top than y?"  (default = min-heap)
class Heap {
  constructor(before = (x, y) => x < y) { this.a = []; this.before = before; }
  size() { return this.a.length; }
  peek() { return this.a[0]; }
  push(v) {                          // put it at the bottom, then climb
    const a = this.a; a.push(v);
    let i = a.length - 1;
    while (i > 0) {
      const p = (i - 1) >> 1;
      if (!this.before(a[i], a[p])) break;
      [a[i], a[p]] = [a[p], a[i]]; i = p;
    }
  }
  pop() {                            // take the top, put the last one on top, sink it
    const a = this.a;
    if (a.length === 0) return null;
    const top = a[0], last = a.pop();
    if (a.length > 0) {
      a[0] = last;
      let i = 0;
      for (;;) {
        const l = 2 * i + 1, r = l + 1; let best = i;
        if (l < a.length && this.before(a[l], a[best])) best = l;
        if (r < a.length && this.before(a[r], a[best])) best = r;
        if (best === i) break;
        [a[i], a[best]] = [a[best], a[i]]; i = best;
      }
    }
    return top;
  }
}

// A priority queue: items with a priority number (smaller = more urgent).
// Each entry is [priority, arrivalNumber, name]; the arrival number breaks ties fairly.
class PriorityQueue {
  constructor() {
    this.heap = new Heap((x, y) => (x[0] !== y[0] ? x[0] < y[0] : x[1] < y[1]));
    this.arrivals = 0;
  }
  enqueue(name, priority) { this.heap.push([priority, this.arrivals++, name]); }
  dequeue() {
    const top = this.heap.pop();
    return top === null ? null : top[2];
  }
}

const clinic = new PriorityQueue();
clinic.enqueue('sprain', 4);
clinic.enqueue('check-up', 5);
clinic.enqueue('fever', 2);
clinic.enqueue('cut', 2);                 // same urgency as fever, arrived later
clinic.enqueue('chest pain', 1);
let next;
while ((next = clinic.dequeue()) !== null) console.log(next);
// chest pain, fever, cut, sprain, check-up

Java

import java.util.*;
import java.util.function.BiPredicate;

public class Main {
    // A heap lives in a plain list. Spot i has children at 2*i+1 and 2*i+2.
    // before(x, y) answers: "does x belong closer to the top than y?"
    static class Heap<T> {
        private final List<T> a = new ArrayList<>();
        private final BiPredicate<T, T> before;

        Heap(BiPredicate<T, T> before) { this.before = before; }

        int size() { return a.size(); }

        void push(T v) {                          // put it at the bottom, then climb
            a.add(v);
            int i = a.size() - 1;
            while (i > 0) {
                int p = (i - 1) / 2;
                if (!before.test(a.get(i), a.get(p))) break;
                Collections.swap(a, i, p);
                i = p;
            }
        }

        T pop() {                                 // take the top, put the last one on top, sink it
            if (a.isEmpty()) return null;
            T top = a.get(0);
            T last = a.remove(a.size() - 1);
            int n = a.size();
            if (n > 0) {
                a.set(0, last);
                int i = 0;
                while (true) {
                    int l = 2 * i + 1, r = l + 1, best = i;
                    if (l < n && before.test(a.get(l), a.get(best))) best = l;
                    if (r < n && before.test(a.get(r), a.get(best))) best = r;
                    if (best == i) break;
                    Collections.swap(a, i, best);
                    i = best;
                }
            }
            return top;
        }
    }

    // A priority queue: items with a priority number (smaller = more urgent).
    // The arrival number breaks ties fairly.
    record Entry(int priority, int arrival, String name) {}

    static class PriorityQueue {
        private final Heap<Entry> heap = new Heap<>((x, y) ->
            x.priority() != y.priority() ? x.priority() < y.priority() : x.arrival() < y.arrival());
        private int arrivals = 0;

        void enqueue(String name, int priority) {
            heap.push(new Entry(priority, arrivals++, name));
        }

        String dequeue() {
            Entry top = heap.pop();
            return top == null ? null : top.name();
        }
    }

    public static void main(String[] args) {
        PriorityQueue clinic = new PriorityQueue();
        clinic.enqueue("sprain", 4);
        clinic.enqueue("check-up", 5);
        clinic.enqueue("fever", 2);
        clinic.enqueue("cut", 2);               // same urgency as fever, arrived later
        clinic.enqueue("chest pain", 1);
        String next;
        while ((next = clinic.dequeue()) != null) System.out.println(next);
        // chest pain, fever, cut, sprain, check-up
    }
}

Go

package main

import "fmt"

// A heap lives in a plain slice. Spot i has children at 2*i+1 and 2*i+2.
// before(x, y) answers: "does x belong closer to the top than y?"
type Heap[T any] struct {
	a      []T
	before func(x, y T) bool
}

func (h *Heap[T]) Size() int { return len(h.a) }

// Push puts it at the bottom, then climbs.
func (h *Heap[T]) Push(v T) {
	h.a = append(h.a, v)
	i := len(h.a) - 1
	for i > 0 {
		p := (i - 1) / 2
		if !h.before(h.a[i], h.a[p]) {
			break
		}
		h.a[i], h.a[p] = h.a[p], h.a[i]
		i = p
	}
}

// Pop takes the top, puts the last one on top, and sinks it.
func (h *Heap[T]) Pop() (T, bool) {
	var zero T
	if len(h.a) == 0 {
		return zero, false
	}
	top := h.a[0]
	last := h.a[len(h.a)-1]
	h.a = h.a[:len(h.a)-1]
	n := len(h.a)
	if n > 0 {
		h.a[0] = last
		i := 0
		for {
			l, r, best := 2*i+1, 2*i+2, i
			if l < n && h.before(h.a[l], h.a[best]) {
				best = l
			}
			if r < n && h.before(h.a[r], h.a[best]) {
				best = r
			}
			if best == i {
				break
			}
			h.a[i], h.a[best] = h.a[best], h.a[i]
			i = best
		}
	}
	return top, true
}

// A priority queue: items with a priority number (smaller = more urgent).
// The arrival number breaks ties fairly.
type entry struct {
	priority, arrival int
	name              string
}

type PriorityQueue struct {
	heap     *Heap[entry]
	arrivals int
}

func NewPriorityQueue() *PriorityQueue {
	return &PriorityQueue{heap: &Heap[entry]{before: func(x, y entry) bool {
		if x.priority != y.priority {
			return x.priority < y.priority
		}
		return x.arrival < y.arrival
	}}}
}

func (q *PriorityQueue) Enqueue(name string, priority int) {
	q.heap.Push(entry{priority, q.arrivals, name})
	q.arrivals++
}

func (q *PriorityQueue) Dequeue() (string, bool) {
	top, ok := q.heap.Pop()
	return top.name, ok
}

func main() {
	clinic := NewPriorityQueue()
	clinic.Enqueue("sprain", 4)
	clinic.Enqueue("check-up", 5)
	clinic.Enqueue("fever", 2)
	clinic.Enqueue("cut", 2) // same urgency as fever, arrived later
	clinic.Enqueue("chest pain", 1)
	for {
		next, ok := clinic.Dequeue()
		if !ok {
			break
		}
		fmt.Println(next)
	}
	// chest pain, fever, cut, sprain, check-up
}

Time: O(log n) per enqueue and per dequeue · Extra space: O(n). A heap gives both actions in logarithmic time; a sorted list would make one of them O(n).

Watch out for

  • Calling any heap a "queue" and expecting first-in first-out. A priority queue serves by priority, not by arrival.
  • Forgetting a tie-breaker. Equal priorities may come out in a surprising order unless you add an arrival counter.
  • Keeping a plain sorted array and inserting into it. Each insert then costs O(n) instead of O(log n).

Quick check

  1. A priority queue returns the next item by...
    • Priority
    • Alphabetical order
    • Arrival time
  2. What is usually used under the hood?
    • A hash map
    • A heap
    • A linked list
  3. How do you serve equal priorities fairly?
    • Pick randomly
    • Add an arrival counter as a second key
    • Delete one of them