progress

~/problems / Streams & durability / Fault-tolerant work queue

Round-robin print queue across customers

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 copy shop has one printer. So one customer's 500 flyers don't block everyone, it serves customers in turns: one job per customer, then the next waiting customer.

Build FairQueue with:

  • submit(customer, job_id): add a job to that customer's queue. A customer with no pending jobs joins the back of the rotation.
  • next_job() -> tuple[str, str] | None: the front customer's oldest job as (customer, job_id). If they still have jobs, they go to the back; otherwise they leave. None if nothing is pending.
  • pending(customer) -> int: that customer's waiting jobs (0 if unknown).

Job ids are unique strings.

q = FairQueue()
q.submit("ann", "a1"); q.submit("ann", "a2"); q.submit("ann", "a3")
q.submit("bo", "b1")
q.next_job()           # ("ann", "a1")
q.submit("cy", "c1")   # cy joins the rotation behind bo and ann
q.next_job()           # ("bo", "b1")    bo is done and leaves the rotation
q.next_job()           # ("ann", "a2")
q.submit("bo", "b2")   # bo had nothing pending: back of the rotation, behind cy
q.next_job()           # ("cy", "c1")
q.next_job()           # ("ann", "a3")
q.next_job()           # ("bo", "b2")
q.next_job()           # None

⭐ Bonus: a speed test with 200,000 jobs earns a star if submit and next_job are O(1): no searching a customer list, no pop(0) on lists.

Show hint

a dict customer -> deque of jobs plus one deque rotation; a customer is in the rotation exactly when their deque is non-empty.

Topic: Fault-tolerant work queue. Leases with deadlines in a min-heap; explicit task states.

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