Priority queue
Intermediate · 10 min · code in PHP, JavaScript, Java and Go
Where you will meet this in real life
A priority queue serves the most important item first, not the oldest. You add items with a priority, and whenever you ask for the next, you get the one with the highest priority. It suits any situation where some things simply cannot wait.
Practical use cases
- Web app: Support tickets by urgency. A helpdesk gets hundreds of tickets, and a "payment failed" ticket must be seen before a "change my avatar" one. Each ticket carries a priority, and the next one an agent takes is always the most urgent, not the oldest. Important customers no longer wait behind trivial requests.
- Web app: Job queue with urgent and bulk tasks. An app sends password-reset emails and weekly newsletters through the same queue. Giving resets a higher priority means they leave immediately, even if 50,000 newsletter jobs were queued first. Users get their reset link in seconds, and the newsletter jobs simply continue afterwards.
- System: Schedulers, routing and compression. Operating systems pick which program runs next by priority. Map apps use it to explore the cheapest routes first, and file compressors use it to repeatedly pick the two rarest symbols.
The story: The Clinic Where the Sickest Goes First
Dr. Fatima ran a small clinic in a busy market lane. Her first rule was a normal queue: first come, first served. One afternoon a man with a mild cold arrived early and sat patiently. Twenty minutes later a worried father carried in a child struggling to breathe, and joined the back of the line.
Nurse Asha saw it and did not wait. "Doctor, this child cannot wait behind a cold!" The doctor agreed on the spot. From that day every patient got a number on a slip: 1 for emergencies, 2 for painful injuries, 3 for fevers, 4 for small things. The doctor always took the slip with the smallest number.
What about two patients with the same number? Asha added a tiny rule: the one who came earlier goes first. Mira, who was waiting with her grandfather, whispered: "So it is a queue where importance decides who is next, not just arrival time." Exactly: that is a priority queue. Behind the scenes it is usually built on a heap, a tree that keeps the most urgent item at the top without sorting the whole line.
How to spot this problem, and where you need it
Items arrive all the time but some matter more than others, and a plain first-come-first-served line makes urgent things wait behind unimportant ones.
Signs you need it
- The requirement says "most urgent first", "highest score first", "smallest cost next" or "process by priority".
- You re-sort the full array every time one item is added just to pick the best one.
- A shortest-path, scheduling or "top K" problem keeps asking for the current best candidate.
Where to use it in a project
- Ticketing, triage and moderation queues where urgency matters.
- Background job systems with high-priority and low-priority work.
- Route and shortest-path features, event timers and "top K" lists.
The solution
Store the items in a heap, a tree-shaped arrangement where the best item is always at the top. To add an item, place it at the bottom and let it float up while it beats its parent. To take the best, remove the top, move the last item to the top and let it sink to its right place. Both steps take only a handful of swaps.
Payoff: Before: re-sorting 100,000 waiting items after each arrival. After: about 17 swaps per add or removal.
Explain it like I am 8
Think of a school canteen where the teacher always serves the smallest kid first, no matter who stood in line earlier. Whenever someone new arrives, the teacher quickly checks if they are smaller than the others. The next one served is always the one that matters most.
How it works, step by step
- Every item is stored together with a priority (here: smaller number = more urgent).
- Insert: add the item at the end of a heap array, then let it "float up" while it is more urgent than its parent.
- Extract: the most urgent item is always at the top (index 0). Take it out, move the last item to the top, and let it "sink down" below any more urgent child.
- For ties, store an arrival counter and compare it too, so equal priorities leave in arrival order.
- You never sort everything: only one path in the tree gets fixed, so each operation is quick.
The code in four languages
PHP
<?php
// Min-heap priority queue. Items are [priority, arrivalNumber, name].
class PriorityQueue {
private array $h = [];
private int $seq = 0;
private function less(array $a, array $b): bool {
// lower priority number wins; earlier arrival breaks ties
return $a[0] < $b[0] || ($a[0] === $b[0] && $a[1] < $b[1]);
}
public function push(string $name, int $priority): void {
$this->h[] = [$priority, $this->seq++, $name];
$i = count($this->h) - 1;
while ($i > 0) { // float up
$p = intdiv($i - 1, 2);
if (!$this->less($this->h[$i], $this->h[$p])) break;
[$this->h[$i], $this->h[$p]] = [$this->h[$p], $this->h[$i]];
$i = $p;
}
}
public function pop(): ?string {
if (!$this->h) return null;
$top = $this->h[0];
$last = array_pop($this->h);
if ($this->h) {
$this->h[0] = $last;
$i = 0; $n = count($this->h);
while (true) { // sink down
$l = 2 * $i + 1; $r = $l + 1; $best = $i;
if ($l < $n && $this->less($this->h[$l], $this->h[$best])) $best = $l;
if ($r < $n && $this->less($this->h[$r], $this->h[$best])) $best = $r;
if ($best === $i) break;
[$this->h[$i], $this->h[$best]] = [$this->h[$best], $this->h[$i]];
$i = $best;
}
}
return $top[2];
}
}
$pq = new PriorityQueue();
$pq->push('Fever', 3);
$pq->push('Fracture', 2);
$pq->push('Heart attack', 1);
$pq->push('Cold', 4);
$pq->push('Cut', 2);
while (($p = $pq->pop()) !== null) echo $p . "\n";
// Heart attack, Fracture, Cut, Fever, Cold
JavaScript
// Min-heap priority queue. Items are [priority, arrivalNumber, name].
class PriorityQueue {
constructor() { this.h = []; this.seq = 0; }
less(a, b) {
// lower priority number wins; earlier arrival breaks ties
return a[0] < b[0] || (a[0] === b[0] && a[1] < b[1]);
}
push(name, priority) {
this.h.push([priority, this.seq++, name]);
let i = this.h.length - 1;
while (i > 0) { // float up
const p = Math.floor((i - 1) / 2);
if (!this.less(this.h[i], this.h[p])) break;
[this.h[i], this.h[p]] = [this.h[p], this.h[i]];
i = p;
}
}
pop() {
if (this.h.length === 0) return null;
const top = this.h[0];
const last = this.h.pop();
if (this.h.length > 0) {
this.h[0] = last;
let i = 0; const n = this.h.length;
while (true) { // sink down
const l = 2 * i + 1, r = l + 1; let best = i;
if (l < n && this.less(this.h[l], this.h[best])) best = l;
if (r < n && this.less(this.h[r], this.h[best])) best = r;
if (best === i) break;
[this.h[i], this.h[best]] = [this.h[best], this.h[i]];
i = best;
}
}
return top[2];
}
}
const pq = new PriorityQueue();
pq.push('Fever', 3);
pq.push('Fracture', 2);
pq.push('Heart attack', 1);
pq.push('Cold', 4);
pq.push('Cut', 2);
let p;
while ((p = pq.pop()) !== null) console.log(p);
// Heart attack, Fracture, Cut, Fever, ColdJava
import java.util.*;
public class Main {
// Min-heap priority queue. Items are (priority, arrivalNumber, name).
static class PriorityQueue {
record Item(int priority, int arrival, String name) {}
private final List<Item> h = new ArrayList<>();
private int seq = 0;
private boolean less(Item a, Item b) {
// lower priority number wins; earlier arrival breaks ties
return a.priority() < b.priority()
|| (a.priority() == b.priority() && a.arrival() < b.arrival());
}
private void swap(int i, int j) {
Item tmp = h.get(i);
h.set(i, h.get(j));
h.set(j, tmp);
}
void push(String name, int priority) {
h.add(new Item(priority, seq++, name));
int i = h.size() - 1;
while (i > 0) { // float up
int p = (i - 1) / 2;
if (!less(h.get(i), h.get(p))) break;
swap(i, p);
i = p;
}
}
String pop() {
if (h.isEmpty()) return null;
Item top = h.get(0);
Item last = h.remove(h.size() - 1);
if (!h.isEmpty()) {
h.set(0, last);
int i = 0, n = h.size();
while (true) { // sink down
int l = 2 * i + 1, r = l + 1, best = i;
if (l < n && less(h.get(l), h.get(best))) best = l;
if (r < n && less(h.get(r), h.get(best))) best = r;
if (best == i) break;
swap(i, best);
i = best;
}
}
return top.name();
}
}
public static void main(String[] args) {
PriorityQueue pq = new PriorityQueue();
pq.push("Fever", 3);
pq.push("Fracture", 2);
pq.push("Heart attack", 1);
pq.push("Cold", 4);
pq.push("Cut", 2);
String p;
while ((p = pq.pop()) != null) System.out.println(p);
// Heart attack, Fracture, Cut, Fever, Cold
}
}Go
package main
import "fmt"
// item is (priority, arrivalNumber, name).
type item struct {
priority int
arrival int
name string
}
// PriorityQueue is a min-heap written by hand.
type PriorityQueue struct {
h []item
seq int
}
func less(a, b item) bool {
// lower priority number wins; earlier arrival breaks ties
return a.priority < b.priority || (a.priority == b.priority && a.arrival < b.arrival)
}
func (pq *PriorityQueue) Push(name string, priority int) {
pq.h = append(pq.h, item{priority, pq.seq, name})
pq.seq++
i := len(pq.h) - 1
for i > 0 { // float up
p := (i - 1) / 2
if !less(pq.h[i], pq.h[p]) {
break
}
pq.h[i], pq.h[p] = pq.h[p], pq.h[i]
i = p
}
}
func (pq *PriorityQueue) Pop() (string, bool) {
if len(pq.h) == 0 {
return "", false
}
top := pq.h[0]
last := pq.h[len(pq.h)-1]
pq.h = pq.h[:len(pq.h)-1]
if len(pq.h) > 0 {
pq.h[0] = last
i, n := 0, len(pq.h)
for { // sink down
l, r, best := 2*i+1, 2*i+2, i
if l < n && less(pq.h[l], pq.h[best]) {
best = l
}
if r < n && less(pq.h[r], pq.h[best]) {
best = r
}
if best == i {
break
}
pq.h[i], pq.h[best] = pq.h[best], pq.h[i]
i = best
}
}
return top.name, true
}
func main() {
pq := &PriorityQueue{}
pq.Push("Fever", 3)
pq.Push("Fracture", 2)
pq.Push("Heart attack", 1)
pq.Push("Cold", 4)
pq.Push("Cut", 2)
for name, ok := pq.Pop(); ok; name, ok = pq.Pop() {
fmt.Println(name)
}
// Heart attack, Fracture, Cut, Fever, Cold
}Time: O(log n) · Extra space: O(n). Push and pop each fix just one path of the heap (the tree is short); peeking at the top is O(1).
Watch out for
- Sorting the whole list after every insert. That works, but costs O(n log n) each time instead of O(log n).
- Mixing up min-heap and max-heap: decide whether "small number" or "big number" means urgent, and keep that in one comparison function.
- Assuming equal priorities come out in arrival order. A plain heap does not promise it; add an arrival counter like we did if you need it.
Quick check
- In a priority queue, who is served next?
- The one who arrived first
- The one with the highest priority
- The one who arrived last
- What structure usually powers a priority queue?
- A heap
- A hash table
- A linked list of sorted pairs only
- Cost of removing the most urgent item from a heap-based priority queue?
- O(1)
- O(n)
- O(log n)