Sub topic 1
What a Priority Queue Does
A priority queue is a collection that always hands back the most urgent item first, no matter the order in which items arrived. This chapter defines the abstract data type (ADT), shows the naive ways to build one, and explains why a heap is the standard answer. The heap itself comes in later chapters.
Prerequisites
This chapter assumes you know:
- Basic Python: lists, functions, loops, and tuples.
- Big-O notation, including what O(log n) means.
- Zero-based array indexing.
You do not need to know trees or heaps yet.
The abstract data type
An ADT describes what operations a structure offers, not how it stores data. A priority queue supports these operations:
| Operation | Meaning |
|---|---|
| `push(item, priority)` | Add an item with a priority |
| `peek()` | Look at the most urgent item without removing it |
| `pop()` | Remove and return the most urgent item |
| `len()` | Report how many items are stored |
"Most urgent" is a convention. In a min-priority queue the smallest priority value wins. In a max-priority queue the largest wins. This tutorial uses min-priority queues, because that is what Python's heapq provides.
A plain queue is first in, first out. A priority queue ignores arrival order. If you push priorities 5, 1, and 3, pops return 1, then 3, then 5.
Two naive implementations
You can build the ADT from a Python list in two obvious ways.
class UnsortedPQ:
def __init__(self):
self._items = []
def __len__(self):
return len(self._items)
def push(self, priority, item):
self._items.append((priority, item)) # O(1)
def pop(self):
if not self._items:
raise IndexError("pop from empty queue")
best = min(range(len(self._items)), key=lambda i: self._items[i][0])
return self._items.pop(best) # O(n)
pq = UnsortedPQ()
pq.push(5, "low")
pq.push(1, "urgent")
pq.push(3, "medium")
print(pq.pop()) # (1, 'urgent')
print(pq.pop()) # (3, 'medium')This version has cheap pushes and slow pops, because each pop scans every item. The opposite design keeps the list sorted. Then the minimum is easy to reach, but each push must find a position and shift items, which costs O(n).
| Design | push | pop | peek |
|---|---|---|---|
| Unsorted list | O(1) | O(n) | O(n) |
| Sorted list | O(n) | O(1) at the right end, O(n) at the left | O(1) |
| Binary heap | O(log n) | O(log n) | O(1) |
Both lists make one operation linear. If a program does n pushes and n pops, either list costs O(n²) in total. A heap brings that to O(n log n).
Where priority queues appear
- Task schedulers run the most urgent job next.
- Dijkstra's shortest-path algorithm repeatedly takes the closest unvisited node.
- Event simulations process the earliest event first.
- Top-k selection keeps only the best k items from a stream.
Later chapters cover the last two of these in detail.
Common mistakes
- Treating the ADT as the implementation. "Priority queue" names a behavior. A heap is one way to provide it.
- Assuming equal priorities come out in insertion order. The ADT does not promise that. Chapter material on tie-breaking shows how to add it.
- Expecting a heap to be fully sorted. A heap only guarantees fast access to the minimum.
Exercise
A program performs 100,000 pushes followed by 100,000 pops on an unsorted-list priority queue. Which operation dominates the total cost, and why does a heap do better?
Show answer
The pops dominate. Each pop scans the whole list, which is O(n), so the 100,000 pops cost O(n²) overall. A heap makes each pop O(log n), so the total drops to O(n log n).