Skip to content
BytePatterns

Priority Queue

Heaps: lesson 3 of 7

Serve by urgency, not by who shouted first.

Lesson 3 of 7 · 5 min

Priority Queue

Step 1 of 14

A berth queue serves by cost of waiting, not by who anchored first. Push a tuple: (priority, tick, ship).

The Idea

A priority queue hands out the most urgent item, whatever time it arrived. A heap is the natural engine: push and pop in O(log n), peek in O(1).

Python's heapq compares whatever you push, so push tuples. Convention is (priority, tiebreak, item) — tuples compare left to right, and the counter both keeps equal priorities in arrival order and stops Python from ever comparing the payloads.

Real-World Example

A container port berths ships by cost of waiting, not by who anchored first. A reefer full of thawing fish outranks a gravel barge that drifted in yesterday, and among equally urgent ships the earlier arrival goes in first.

The Code

import heapq, itertools

berth, tick = [], itertools.count()    # tick breaks ties, keeps FIFO

def request(priority, ship):
    heapq.heappush(berth, (priority, next(tick), ship))

def next_ship():
    return heapq.heappop(berth)[2]     # lowest number = most urgent

for p, s in [(2, "Kestrel"), (1, "Aurora"), (2, "Bellona")]:
    request(p, s)
print(next_ship())                     # Aurora
print(next_ship())                     # Kestrel - tied, but queued first

Python

Your turn

Fill in the blank.

import heapq
dock = []
heapq.heappush(dock, (3, "Kestrel"))
heapq.heappush(dock, (1, "Aurora"))
# should print Aurora, the most urgent ship
print(heapq.heappop(dock)[___])

Mini quiz

1 / 3

Both push and pop on a heap-backed priority queue cost:

New lessons land every few weeks

Leave an address and we will tell you when the next one is up. That is the only reason we will use it.

One address, stored so we can email you. Nothing else, ever.