2/28
Part 1 of 6 · A queue and its holdersLearn and do

A queue hands out the oldest task first

A queue is a line at a counter. New tasks join at the back, and work is taken from the front. So the task that has waited longest goes first. That rule is called FIFO, for first in, first out.

Python's collections.deque is built for this. append adds at the back and popleft takes from the front, and both cost O(1).

from collections import deque

line = deque()
line.append("a")
line.append("b")
line.append("c")
print(line.popleft())
print(line)
a
deque(['b', 'c'])
The line after three enqueues, front on the left
line
abc

reserve takes a, the task that has waited longest. A new task joins after c.

A plain list works too, but list.pop(0) moves every item behind the first one up a place, so it costs O(n). On a queue of a million tasks, that's a million moves for every reserve. Use a deque, or a heap when the order needs more than arrival time. You'll need the heap in part 2.

One more rule from the problem: a reserve on an empty queue returns None. It doesn't raise. Workers ask for work all the time, and "nothing to do" is a normal answer.

The function replay in the editor runs a list of queue operations on a deque. Write the loop body, so each reserve records the task it took, or None.