Skip to content

Queues and round-robin work

A queue removes the earliest added item first. This first-in, first-out rule is abbreviated FIFO. Use a queue when work must proceed in arrival order, including breadth-first search and round-robin service.

Python’s collections.deque supports efficient operations at both ends. Read stacks to compare FIFO with LIFO. The jobs below are invented examples.

For an ordinary queue, add at the right with append and remove at the left with popleft. appendleft adds at the left, and pop removes from the right. Each of these deque operations takes O(1) time. Indexing near the middle takes O(n), so a deque does not replace a list for arbitrary indexed access.

from collections import deque
queue = deque(["A", "B"])
print("Initial:", list(queue))
queue.append("C")
print("Enqueue C:", list(queue))
print("Dequeue:", queue.popleft())
print("Remaining:", list(queue))
queue.appendleft("urgent")
print("Add at left:", list(queue))
print("Remove at right:", queue.pop())
print("Remaining:", list(queue))
Initial: ['A', 'B']
Enqueue C: ['A', 'B', 'C']
Dequeue: A
Remaining: ['B', 'C']
Add at left: ['urgent', 'B', 'C']
Remove at right: C
Remaining: ['urgent', 'B']

Use if queue before removal when the queue might be empty. Avoid list.pop(0) for a large FIFO queue because it shifts all remaining references. Removing every item from a list’s front can take O(n²) total time. A bounded deque(maxlen=...) silently drops an item from the opposite end when full, so this scheduler uses an unbounded deque.

Each job has a name and a positive number of work units. Process one unit from the front job. Return an unfinished job to the back, or record its name if it finishes. Return the names in completion order.

The queue always contains exactly the unfinished jobs in the order of their next turns. Removing the front preserves that order for other jobs. Appending the unfinished job makes it wait behind those jobs before receiving another turn.

def completion_order(jobs: list[tuple[str, int]]) -> list[str]:
"""Return completion order when each queued job receives one work unit.
Args:
jobs: Job names and strictly positive integer work requirements.
Returns:
Job names in completion order under round-robin service.
Raises:
ValueError: If a job has a nonpositive work requirement.
"""
if any(work <= 0 for _, work in jobs):
raise ValueError("Each job must require positive work.")
pending = deque(jobs)
completed = []
while pending:
name, remaining = pending.popleft()
remaining -= 1
if remaining:
pending.append((name, remaining))
else:
completed.append(name)
return completed
jobs = [("A", 2), ("B", 1), ("C", 3)]
pending = deque(jobs)
completed = []
turn = 0
while pending:
turn += 1
name, remaining = pending.popleft()
remaining -= 1
if remaining:
pending.append((name, remaining))
else:
completed.append(name)
print(turn, name, list(pending), completed)
print("Completion order:", completion_order(jobs))
1 A [('B', 1), ('C', 3), ('A', 1)] []
2 B [('C', 3), ('A', 1)] ['B']
3 C [('A', 1), ('C', 2)] ['B']
4 A [('C', 2)] ['B', 'A']
5 C [('C', 1)] ['B', 'A']
6 C [] ['B', 'A', 'C']
Completion order: ['B', 'A', 'C']

The total remaining work decreases by one on every iteration and never becomes negative. This fact proves termination for the stated positive integer inputs. Appending a completed job again would break that argument.

Let n be the number of jobs and T the sum of their work requirements. These costs assume constant-time arithmetic on the work counts. Initialization takes O(n), and the loop executes exactly T turns, so total time is O(n + T). The queue holds at most n jobs, giving O(n) auxiliary space. The returned list also contains n names.

An O(n) time claim would omit repeated turns for unfinished jobs. The displayed trace copies the queue and completed list, so its display work can take O(nT).

assert completion_order([]) == []
assert completion_order([("solo", 4)]) == ["solo"]
assert completion_order([("A", 1), ("B", 1)]) == ["A", "B"]
assert completion_order([("A", 2), ("B", 1)]) == ["B", "A"]
try:
completion_order([("invalid", 0)])
except ValueError as error:
print(type(error).__name__, str(error))
print("Boundary checks passed.")
ValueError Each job must require positive work.
Boundary checks passed.
  • Solve Number of Recent Calls with a queue of relevant timestamps. State why an expired timestamp can leave permanently.
  • Solve Rotting Oranges with breadth-first search. Put all initial sources into the queue before the first layer.

Continue with graphs to use a queue for breadth-first search.

Download the Python source to run the complete example locally.

Python’s deque documentation defines both-end operations, indexing costs, and bounded deques. These details explain the scheduler’s data structure choice.

The Python queue tutorial compares list front removal with a deque. It explains why FIFO behavior alone does not guarantee efficient implementation.