DEV Community

Sreekar Reddy
Sreekar Reddy

Posted on • Originally published at sreekarreddy.com

πŸ† Priority Queues Explained Like You're 5

Highest priority items served first

Day 138 of 149

πŸ‘‰ Full deep-dive with code examples


The Emergency Room Analogy

In an emergency room:

  • You don't go in order of arrival
  • Heart attack patient β†’ First, no matter when they arrived
  • A sprained ankle β†’ Waits, even if they came earlier
  • Priority matters more than arrival time

A Priority Queue lets the highest priority item go first!


How It Differs from Regular Queues

Regular Queue (FIFO):

  • First in, first out
  • Everyone waits their turn
  • Arrival order is everything

Priority Queue:

  • Highest priority out first
  • "Importance" matters, not arrival order
  • The VIP line

How It Works

Each item has a priority:

Add: (Task: "Email", Priority: 3)
Add: (Task: "Bug fix", Priority: 1)  ← Highest priority
Add: (Task: "Meeting", Priority: 2)

Get next: "Bug fix" (priority 1 goes first!)
Get next: "Meeting" (priority 2)
Get next: "Email" (priority 3)
Enter fullscreen mode Exit fullscreen mode

Lower number = higher priority (like hospital triage).


Common Uses

  • Task scheduling β†’ Important tasks first
  • Dijkstra's algorithm β†’ Visit closest node next
  • Huffman coding β†’ Build tree from smallest frequencies
  • Event systems β†’ Process urgent events first
  • Operating systems β†’ Run high-priority processes

Behind the Scenes

Priority queues are usually implemented with heaps:

  • Finding highest priority: instant (O(1))
  • Adding items: fast (O(log n))
  • Removing highest: fast (O(log n))

Priority Queue vs Sorting

Why not just sort?

  • Sorting: O(n log n) to sort everything
  • Priority Queue: O(log n) per operation

Priority queue is better when items come and go!


In One Sentence

A Priority Queue is like a smart line where the most important item goes first, regardless of when it arrived.


πŸ”— Enjoying these? Follow for daily ELI5 explanations!

Making complex tech concepts simple, one day at a time.

Top comments (0)