Sub topic 13
Priority Queues: The Abstract Interface
Prerequisites and scope
This chapter assumes you know the following:
- Arrays and singly linked lists, including the cost of insertion and deletion in each.
- The stack and queue ADTs (abstract data types), including FIFO order.
- Big-O notation at an introductory level.
A priority queue is an abstract data type (ADT). An ADT defines what operations exist and what they promise, not how they are stored. This chapter covers the interface and the cost of simple implementations. The binary heap, the usual efficient implementation, is the next chapter's subject.
From queue to priority queue
A queue serves elements in the order they arrived. A priority queue serves elements in order of importance. Each element carries a key, which is its priority. When you remove an element, you always get the one with the best key, regardless of arrival time.
Two variants exist, and the only difference is which end of the key order counts as "best":
- A min-priority queue removes the element with the smallest key.
- A max-priority queue removes the element with the largest key.
GATE questions usually state which variant is meant. If they don't, read the operation names. extract_min implies a min-priority queue, and extract_max implies a max-priority queue.
The interface
| Operation | Meaning | Returns |
|---|---|---|
| `insert(x, key)` | Add an element with the given priority | nothing |
| `find_min()` (or `peek`) | Look at the best element without removing it | the element |
| `extract_min()` | Remove and return the best element | the element |
| `is_empty()` | Test whether any elements remain | true or false |
Many libraries and textbooks add a fifth operation:
decrease_key(x, new_key)lowers the key of an element already in the structure. Dijkstra's shortest-path algorithm and Prim's minimum spanning tree algorithm both rely on it.
The ADT says nothing about ties. If two elements have equal keys, the interface does not say which comes out first. A priority queue is therefore not stable by default. If you need first-in-first-out order among equal keys, you must add it yourself, for example by using the pair (priority, arrival number) as the key.
Implementation 1: unsorted array or list
Store elements in any order and append new ones at the end.
insertwrites at the end of the array. It costs O(1).find_minandextract_minmust scan every element to find the smallest. They cost O(n).- After removing an element from the middle of an array, you can fill the gap by moving the last element into it. That keeps removal itself at O(1), so the scan dominates.
Implementation 2: sorted array or list
Keep elements in order by key at all times.
find_mincosts O(1) because the best element is at one fixed end.extract_mincosts O(1) if the best element is at the end of an array (so no shifting is needed) or at the head of a linked list.insertmust find the correct position and keep the order. In an array, finding the position takes O(log n) with binary search, but shifting elements to make room takes O(n). In a linked list, the search takes O(n) because there is no random access, but the splice itself is O(1). Both total O(n).
Implementation 3: binary heap
A binary heap keeps the elements only partly ordered, enough to find the best one quickly. It is stored in an array. The following chapters show that this gives O(log n) for insert and extract_min, and O(1) for find_min.
Comparing the implementations
| Implementation | insert | find_min | extract_min |
|---|---|---|---|
| Unsorted array | O(1) | O(n) | O(n) |
| Sorted array (best at the end) | O(n) | O(1) | O(1) |
| Sorted linked list | O(n) | O(1) | O(1) |
| Binary heap | O(log n) | O(1) | O(log n) |
The table shows a trade-off. The two simple approaches make one side cheap and the other side expensive. The heap balances both at O(log n).
A useful consequence: inserting n elements and then extracting all of them yields them in sorted order. This is a sorting algorithm. With the unsorted array it becomes selection sort, which costs O(n²). With the sorted list it becomes insertion sort, which also costs O(n²). With a heap it becomes heap sort, which costs O(n log n).
A runnable model of the interface
The class below implements the interface with an unsorted list. It is deliberately simple, so the interface stays visible. It uses a counter to break ties in arrival order, which makes it stable.
class SimplePQ:
def __init__(self):
self.items = [] # list of (key, arrival, value)
self.counter = 0
def insert(self, value, key):
self.items.append((key, self.counter, value))
self.counter += 1
def is_empty(self):
return len(self.items) == 0
def find_min(self):
if self.is_empty():
raise IndexError('priority queue empty')
return min(self.items)[2]
def extract_min(self):
if self.is_empty():
raise IndexError('priority queue empty')
best = min(self.items)
self.items.remove(best)
return best[2]
pq = SimplePQ()
pq.insert('write report', 3)
pq.insert('fix outage', 1)
pq.insert('reply to mail', 3)
pq.insert('deploy patch', 2)
while not pq.is_empty():
print(pq.extract_min())The output is:
fix outage
deploy patch
write report
reply to mail"write report" comes before "reply to mail" only because of the arrival counter. Both have key 3.
Where priority queues are used
- Operating system schedulers choose the next process by priority.
- Dijkstra's algorithm repeatedly extracts the unvisited vertex with the smallest tentative distance.
- Huffman coding repeatedly extracts the two least frequent symbols and merges them.
- Event simulations process events in order of timestamp.
- Finding the k largest items in a stream keeps a small min-priority queue of size k.
Visualizing the flow
Common errors
- Confusing the ADT with the heap. A priority queue is an interface. A heap is one way to implement it. A question that asks for the cost of "a priority queue" without naming an implementation is incomplete, so look for the stated structure.
- Assuming the whole structure is sorted. A heap does not keep elements fully sorted. Only the best element is guaranteed to be easy to reach.
- Mixing up min and max. Check which end
extractremoves before you trace an example. - Expecting first-in-first-out among ties. The ADT gives no such guarantee.
- Counting sorted-array insertion as O(log n). Binary search finds the position in O(log n), but shifting the elements still costs O(n).
- Forgetting underflow. Extracting from an empty structure must be handled.
Choosing an implementation
Match the structure to the workload:
- Many inserts and few extractions: an unsorted array makes inserts O(1).
- Few inserts and many extractions or peeks: a sorted structure makes those O(1).
- A mixed workload with large n: a binary heap, since neither side is O(n).
- A small, fixed number of distinct priority values: a separate FIFO queue per priority level can give O(1) operations, at the cost of extra memory and a bound on the number of levels.
Exercise
A min-priority queue is implemented as a sorted singly linked list with the smallest key at the head. State the worst-case time for insert, findmin, and extractmin, and say how many comparisons insert needs in the worst case when the list holds n elements.
Show answer
insert is O(n), findmin is O(1), and extractmin is O(1). In the worst case the new key is larger than every existing key, so insert compares it against all n elements, which is n comparisons, before placing it at the tail.
Exercise
Starting from an empty min-priority queue, the operations are insert 5, insert 2, insert 8, extractmin, insert 1, extractmin, extract_min. List the values returned by the three extractions in order.
Show answer
2, 1, 5. After the first three inserts the queue holds 5, 2, and 8, so the first extraction returns 2. Then 1 is inserted, so the queue holds 5, 8, and 1, and the second extraction returns 1. The third extraction returns 5, leaving 8.
Exercise
Why does inserting n elements into a priority queue and then extracting all of them always produce a sorted sequence, and what does the total cost become with an unsorted array as the implementation?
Show answer
Every extract_min returns the smallest key still present, so each returned value is at least as large as the one before it, which means the output is in non-decreasing order. With an unsorted array, each of the n insertions costs O(1) and each of the n extractions costs O(n), so the total is O(n²). This is selection sort.