progress

~/problems / Heaps / Heaps and priority queues

Help desk by urgency

On a phone? Coding is easier on a laptop: email this problem to yourself . Meanwhile: quiz this topic or fight a boss.

easy ~15 min

A repair shop's help desk serves customers by urgency, not arrival. The day's log is a list of events:

  • ("arrive", name, urgency): a customer joins the waiting area (bigger urgency means more urgent).
  • ("serve",): the clerk calls the waiting customer with the highest urgency; on a tie, the one who arrived first. If nobody is waiting, skip it.

Write serve_order(events: list[tuple]) -> list[str]: the names in the order they were served.

serve_order([
    ("arrive", "ana", 2),
    ("arrive", "bo", 5),
    ("arrive", "cy", 5),
    ("serve",),            # bo  (urgency 5, arrived before cy)
    ("arrive", "di", 9),
    ("serve",),            # di
    ("serve",),            # cy
    ("serve",),            # ana
    ("serve",),            # nobody waiting: skipped
])
# ["bo", "di", "cy", "ana"]

Up to 200,000 events. Urgencies may be negative. Two customers can share a name, so don't break ties by name.

⭐ Bonus: a speed test with 134,000 events earns a star if each event costs O(log n) with heapq instead of scanning the waiting area.

Show hint

push (-urgency, arrival_number, name): the negation puts the most urgent on top, and the counter breaks ties by arrival.

Topic: Heaps and priority queues. heapq: top-k, k-way merge, two heaps for a running median.

Read the visual guide
0:00
Ctrl ' run · Ctrl ↵ submit
esc