B2.2.4 Queues: first in, first out
SL + HLCommand term: Explain1. The reservation waitlist: first in, first out
Everyone wants the new copy of Dune. Students join at the rear and are served from the front, in the order they arrived. Step through the four queue operations.
2. Queue machine: three implementations
Operate the same queue three ways. A plain Python list must shift every item on dequeue; a deque does not; a circular array reuses a fixed block of memory by wrapping the front and rear pointers around.
- Returns: -3. Performance race: serve the whole queue
Enqueue N students, then dequeue them all. Each bar is the work (elements touched) for one dequeue.
4. Fair or unfair? Queue versus stack
Students reserve a book one by one, then copies come back. Serve them with a queue and with a stack and compare who waits longest.
5. Flip-card deck
Click to flip. Say the answer before you flip.
6. Which queue operation?
Each situation uses a queue. Which operation is happening? Streaks of 3+ score double.
7. 45-second speed round: trace the queue
A new sequence each time. What is the answer?
deque, then use them to reserve a book and to hand returned copies to the next student.Expected output
Think about it
(1) Why is deque.popleft() better than list.pop(0) for a long waitlist? (2) Ben cancels his reservation. A pure queue has no operation to remove someone from the middle: what would you have to do? (3) Every book needs its own waitlist. How might Sprint 3 store many queues?
Check my code
Practical tasks
Three tasks for this topic, from Average to Moderate to Challenging. Start with the first and work up. Each coding task gives you a starter file with tests already written; you write the missing code.
- Open your PyCharm project (or New Project → pure Python, name it
ib_cs_tasks). - Right-click the project → New → Python File, using the file name shown on the task.
- Press Copy starter and paste it in, or press Download .py.
- Right-click in the editor → Run (Windows Shift+F10, Mac Ctrl+R).
- Replace each
pass # your code herewith your own code. Do not change the code below# ---- tests ----. - Run the file and compare your output with Expected output. A crash or an
AssertionErrormeans something is not right yet. - Stuck for more than 10 minutes? Open the Hint. Open the Model solution only after a real attempt, then compare it with yours.
- Written parts: answer in your notebook first, then check the model answer.
Task 1: Serve the queue
Use collections.deque as a queue. Write serve(arrivals, n) that enqueues every name in arrivals, then dequeues and prints "serving NAME" for the first n people, and returns the list of people still waiting.
Starter file (write your code where it says pass # your code here):
from collections import deque
def serve(arrivals, n):
pass # your code here
# ---- tests ----
print(serve(["Ana", "Ben", "Cai", "Dev"], 2))
print(serve(["Eli"], 5))
Expected output when your code is correct:
serving Ana serving Ben ['Cai', 'Dev'] serving Eli []
Hint
append adds at the rear; popleft removes from the front.Model solution
from collections import deque
def serve(arrivals, n):
q = deque()
for name in arrivals:
q.append(name)
for _ in range(min(n, len(q))):
print("serving", q.popleft())
return list(q)
# ---- tests ----
print(serve(["Ana", "Ben", "Cai", "Dev"], 2))
print(serve(["Eli"], 5))
Task 2: Canteen queue simulation
Simulate the canteen queue minute by minute using a plain list as a queue (append to join at the back, pop(0) to serve from the front). arrivals[m] is the list of students who join in minute m, and the server serves rate students per minute after the arrivals. Write simulate(arrivals, rate) that returns each student's waiting time in minutes, the longest queue length, and the average wait rounded to 2 decimal places.
Starter file (write your code where it says pass # your code here):
def simulate(arrivals, rate):
pass # your code here
# ---- tests ----
arrivals = [["Ana", "Ben", "Cai"], ["Dev"], [], ["Eli", "Fay", "Gus", "Hui"]]
print(simulate(arrivals, 1))
print(simulate(arrivals, 2))
Expected output when your code is correct:
({'Ana': 0, 'Ben': 1, 'Cai': 2, 'Dev': 2, 'Eli': 1, 'Fay': 2, 'Gus': 3, 'Hui': 4}, 5, 1.88)
({'Ana': 0, 'Ben': 0, 'Cai': 1, 'Dev': 0, 'Eli': 0, 'Fay': 0, 'Gus': 1, 'Hui': 1}, 4, 0.38)
Hint
Model solution
def simulate(arrivals, rate):
queue = []
waits = {}
longest = 0
minute = 0
while minute < len(arrivals) or queue:
if minute < len(arrivals):
for name in arrivals[minute]:
queue.append((name, minute))
longest = max(longest, len(queue))
for _ in range(min(rate, len(queue))):
name, joined = queue.pop(0)
waits[name] = minute - joined
minute += 1
average = round(sum(waits.values()) / len(waits), 2)
return waits, longest, average
# ---- tests ----
arrivals = [["Ana", "Ben", "Cai"], ["Dev"], [], ["Eli", "Fay", "Gus", "Hui"]]
print(simulate(arrivals, 1))
print(simulate(arrivals, 2))
Task 3: The hot potato game
Children stand in a circle passing a book. Every k-th pass, the child holding it leaves. Use a queue to simulate it: hot_potato(names, k) returns the order in which children leave and the winner. Passing = dequeue the front child and enqueue them at the back.
Starter file (write your code where it says pass # your code here):
from collections import deque
def hot_potato(names, k):
pass # your code here
# ---- tests ----
print(hot_potato(["Ana", "Ben", "Cai", "Dev", "Eli", "Fay"], 3))
print(hot_potato(["Ana", "Ben", "Cai"], 1))
Expected output when your code is correct:
(['Cai', 'Fay', 'Dev', 'Ben', 'Eli'], 'Ana') (['Ana', 'Ben'], 'Cai')
Hint
Model solution
from collections import deque
def hot_potato(names, k):
q = deque(names)
out = []
while len(q) > 1:
for _ in range(k - 1):
q.append(q.popleft())
out.append(q.popleft())
return out, q[0]
# ---- tests ----
print(hot_potato(["Ana", "Ben", "Cai", "Dev", "Eli", "Fay"], 3))
print(hot_potato(["Ana", "Ben", "Cai"], 1))
Learning objectives
By the end of this page you should be able to:
- Explain what "first in, first out" (FIFO) means and why a queue behaves that way.
- Describe and use the fundamental operations enqueue, dequeue, front and isEmpty, and predict the state of a queue after a sequence of operations.
- Explain how the implementation affects performance and memory usage: list.pop(0) is O(n), deque and circular arrays are O(1); fixed arrays can overflow, dynamic queues grow.
- Construct a queue in Python with collections.deque, and trace a circular array queue with front and rear pointers.
- Identify problems for which a queue is appropriate, such as waitlists, print spooling, buffers and scheduling, and justify the choice over a stack.
What is a queue?
A queue is an abstract data type in which items join at one end, the rear (or tail), and leave from the other, the front (or head). The first item added is the first one removed: first in, first out (FIFO), like a line at the issue desk.
The operations
| Operation | What it does | Python deque | Java Queue | Cost |
|---|---|---|---|---|
| enqueue(x) | Add x at the rear | q.append(x) | q.add(x) / q.offer(x) | O(1) |
| dequeue() | Remove and return the front item | q.popleft() | q.remove() / q.poll() | O(1) |
| front() | Return the front item without removing it | q[0] | q.peek() | O(1) |
| isEmpty() | True if there are no items | len(q) == 0 | q.isEmpty() | O(1) |
In Python: from collections import deque, then q = deque(). In Java: Queue<String> q = new LinkedList<>();. Dequeuing an empty queue is underflow.
Performance and memory
- Python list:
appendis O(1), butpop(0)shifts every remaining item left: O(n). Serving n students costs about n²/2 moves. Fine for a handful of items, poor for long queues. - deque (double-ended queue) or a linked list: both ends are O(1). Memory grows and shrinks with the queue (dynamic), with a small overhead per item or block.
- Circular array (static): a fixed block of SIZE slots with a front pointer, a rear pointer and a count. Pointers advance with
(i + 1) % SIZE, so freed slots at the start are reused. O(1) and predictable memory, but it overflows when all SIZE slots are full, and unused slots are wasted. - A simple (non-circular) array queue wastes the slots at the front once items leave, unless everything is shifted back: the circular design fixes that.
Circular array queue
SIZE = 6
items = [None] * SIZE
front = 0
rear = SIZE - 1 # so the first enqueue goes into index 0
count = 0
def enqueue(x):
global rear, count
if count == SIZE:
raise OverflowError("queue is full")
rear = (rear + 1) % SIZE # wrap around to 0 after the last slot
items[rear] = x
count = count + 1
def dequeue():
global front, count
if count == 0:
raise IndexError("queue is empty")
x = items[front]
front = (front + 1) % SIZE
count = count - 1
return x
When is a queue appropriate?
Whenever items must be processed in the order they arrive, fairly:
- Reservation waitlists; customers at a desk; call centres.
- Print spooling: documents print in the order sent.
- Buffers: keyboard input, data streaming between devices of different speeds.
- Scheduling: processes waiting for the CPU (round robin), network packets in a router.
- Breadth-first search: visiting nodes level by level.
Use a stack instead when the most recent item must come first (undo); use a list when you need any position.
Use the 中文 button at the top to show or hide the Chinese terms.
| Term | 中文 | Meaning |
|---|
Choose an answer. You get instant feedback.
Score: 0 /
Write your answer first, then reveal the markscheme. These are exam-style practice questions written for this site.
1. Explain why a queue is described as a FIFO data structure. [2]
2. An empty queue Q has these operations applied: enqueue(5), enqueue(8), dequeue(), enqueue(3), front(), enqueue(6), dequeue(). State (a) the values returned by dequeue and front, in order, (b) the contents of Q from front to rear. [3]
3. A queue is implemented with a Python list, using append to enqueue and pop(0) to dequeue. Explain why this is inefficient for a long queue, and suggest an alternative. [3]
4. A circular queue has SIZE 5, front = 3, rear = 1 and count = 4. Item X is enqueued. State (a) the index where X is stored, (b) the new count, (c) whether another enqueue would succeed. [3]
5. Compare a circular array and a dynamic (linked or deque) implementation of a queue in terms of memory usage. [3]
6. Explain why a queue, rather than a stack, is appropriate for the ShelfWise reservation waitlist. [3]