Skip to content

Data Structures

Priority Queue

With a simple sorted list, as shown below: enqueue is O(n), dequeue is O(1). With a heap (see Min-Heap), both become O(log n). A heap is the standard real-world choice for a priority queue.

The idea, in plain English

A priority queue works like airport boarding, not a coffee line. It doesn't matter who arrived at the gate first. Whoever has the best priority, like first class, then priority members, then everyone else, boards next. Every item carries a priority number. The item that leaves next always has the best priority, not the oldest one.

How it works

  1. 1enqueue(item, priority): add the item along with its priority number.
  2. 2dequeue(): find and remove whichever item currently has the best priority. Here, the lowest number is the best.
  3. 3peek(): look at what would leave next, without removing it.

When you'd use it

Use a priority queue for task schedulers, hospital triage, or turn-based games, where 'most important next' matters more than 'arrived first.' Use it anywhere arrival order shouldn't decide who goes next.

Common beginner mistakes

  • Don't confuse it with a regular queue. A priority queue lets a brand-new item cut straight to the front, if its priority is high enough.
  • Decide up front whether a lower number or a higher number means more urgent. Don't mix the two up while adding items.

Try it — edit and run

Click the code to edit · press ⌘/Ctrl+↵ to run

Editable code. Tab and Shift+Tab indent. Press Escape, then Tab, to move focus out of the editor.

Expected output — hit Run to try it
Boards next: first-class
Board: first-class
Board: priority
Remaining: 1

See it in motion

Watch it boardPriority queuelow = urgentWith a simple sorted list, as shown below: enqueue is O(n), dequeue is O(1). With a heap (see Min-Heap), both become O(log n). A heap is the standard real-world choice for a priority queue.
Backing array
empty
Boarded (best first)
—

Empty queue. Enqueue tasks — lower number = more urgent.

0
In queue
—
Next out
0
Boarded
0.0s
Time
ComparingSwappingMost urgentWaiting

Not sure this is the right topic? See the learning paths → or where this leads →