Home › Theme B › B2 › B2.2 › B2.2.4

B2.2.4 Queues: first in, first out

SL + HLCommand term: Explain

1. 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.

Implementation: Python listcollections.dequeCircular array, size 6
Code: -   Returns: -
Enqueue some students.

3. Performance race: serve the whole queue

Enqueue N students, then dequeue them all. Each bar is the work (elements touched) for one dequeue.

Students: 20

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.

Queue (FIFO)
Stack (LIFO)
Reserve a few students, then return copies.

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.

Round 0/10Score 0Streak 0Best 0
Press start!

7. 45-second speed round: trace the queue

A new sequence each time. What is the answer?

Time 45sScore 0Streak 0Best 0
Press start!
ShelfWise · Sprint 2, task 4. Popular books need a fair reservation waitlist: first to reserve, first to borrow. Write the four queue operations on a deque, then use them to reserve a book and to hand returned copies to the next student.

Expected output

Ana joins the waitlist at position 1 Ben joins the waitlist at position 2 Ana is already waiting Chen joins the waitlist at position 3 ['Ana', 'Ben', 'Chen'] Ana Notify Ana: Dune is ready Notify Ben: Dune is ready ['Chen'] 1 Notify Chen: Dune is ready Copy back on the shelf Dev borrows Dune now True 0

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

    Sprint 2 complete. Next sprint (B2.3): ShelfWise gets proper program flow: sequence, selection, loops and functions for a menu-driven console app.

    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.

    Set up in PyCharm
    1. Open your PyCharm project (or New Project → pure Python, name it ib_cs_tasks).
    2. Right-click the project → New → Python File, using the file name shown on the task.
    3. Press Copy starter and paste it in, or press Download .py.
    4. Right-click in the editor → Run (Windows Shift+F10, Mac Ctrl+R).
    How the tasks work
    1. Replace each pass # your code here with your own code. Do not change the code below # ---- tests ----.
    2. Run the file and compare your output with Expected output. A crash or an AssertionError means something is not right yet.
    3. Stuck for more than 10 minutes? Open the Hint. Open the Model solution only after a real attempt, then compare it with yours.
    4. Written parts: answer in your notebook first, then check the model answer.
    Average

    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):

    File: b2_2_4_average.py
    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
    File: b2_2_4_average_solution.py
    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))
    
    Moderate

    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):

    File: b2_2_4_moderate.py
    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
    Store each student together with the minute they joined, so the wait is (minute served − minute joined).
    Model solution
    File: b2_2_4_moderate_solution.py
    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))
    
    Challenging

    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):

    File: b2_2_4_challenging.py
    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
    Pass k - 1 times (move front to back), then remove the front child.
    Model solution
    File: b2_2_4_challenging_solution.py
    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:

    1. Explain what "first in, first out" (FIFO) means and why a queue behaves that way.
    2. Describe and use the fundamental operations enqueue, dequeue, front and isEmpty, and predict the state of a queue after a sequence of operations.
    3. 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.
    4. Construct a queue in Python with collections.deque, and trace a circular array queue with front and rear pointers.
    5. 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

    OperationWhat it doesPython dequeJava QueueCost
    enqueue(x)Add x at the rearq.append(x)q.add(x) / q.offer(x)O(1)
    dequeue()Remove and return the front itemq.popleft()q.remove() / q.poll()O(1)
    front()Return the front item without removing itq[0]q.peek()O(1)
    isEmpty()True if there are no itemslen(q) == 0q.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: append is O(1), but pop(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]

    Items are added at the rear and removed from the front [1]; so the first item added is the first one removed / items leave in the order they arrived [1].

    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]

    (a) dequeue returns 5 [1]; front returns 8, then dequeue returns 8 [1]. (b) 3, 6 (3 at the front) [1].

    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]

    pop(0) removes the first element, so every remaining element must shift one place left [1]; this takes O(n) time per dequeue / slows down as the queue grows [1]. Use collections.deque with popleft(), or a circular array / linked list, which dequeue in O(1) [1].

    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]

    (a) rear = (1 + 1) % 5 = 2 [1]; (b) count = 5 [1]; (c) no: count equals SIZE, so the queue is full and another enqueue would overflow [1].

    5. Compare a circular array and a dynamic (linked or deque) implementation of a queue in terms of memory usage. [3]

    Circular array: memory for SIZE items is reserved in advance, so it is predictable but wasted when the queue is short [1], and it overflows when full [1]. Dynamic: memory grows and shrinks with the number of items, so it does not overflow until memory is exhausted, but each item/block has pointer overhead [1].

    6. Explain why a queue, rather than a stack, is appropriate for the ShelfWise reservation waitlist. [3]

    Students should receive the book in the order they reserved it [1]; a queue serves the front (earliest) student first / FIFO [1]; a stack would serve the most recent reservation first, so early students could wait indefinitely, which is unfair [1].