Skip to contentKEEP THE CRAFTTHE SANCTUARY

Queue

A queue removes the oldest pending item first. Use deque for FIFO traversal, freeze breadth-layer boundaries, or use head, tail and size to distinguish full from empty when bounded storage wraps.

9 practice exercises17 interview problems

Recognize it when Processing follows arrival order or unweighted graph distance.

Checking your account…

Queue Code Labs

Mental Model

A queue preserves arrival order: the oldest pending item leaves first. That FIFO rule separates a queue from a stack and makes it the natural frontier for breadth-first exploration, scheduling, and stream processing. At every moment, queued items are discovered but not yet processed.

FIFO State with deque

Use collections.deque: append enqueues on the right and popleft dequeues from the left, both in O(1) time. A Python list’s pop(0) shifts every remaining reference and costs O(n). The deque documentation(opens in a new tab) also provides two-ended operations, but a queue deliberately uses only one input and one output end.

Process One Breadth Layer

In breadth-first work, mark an item seen when enqueuing it, not when later removing it. Then each reachable item enters once. To preserve layers, capture the queue length before processing the current batch; newly discovered items belong to the next layer.

Collect Breadth-First Layers

Reference
from collections import deque

def breadth_layers(adjacency, start):
    queue = deque([start])
    seen = {start}
    layers = []
    while queue:
        layer = []
        for _ in range(len(queue)):
            node = queue.popleft()
            layer.append(node)
            for neighbor in adjacency[node]:
                if neighbor not in seen:
                    seen.add(neighbor)
                    queue.append(neighbor)
        layers.append(layer)
    return layers
Practice

Implement breadth_layers(adjacency, start). Return reachable nodes grouped by unweighted distance, marking each node seen when it is enqueued. adjacency is a nonempty list with valid start and neighbor vertex indices.

Public tests

  • Verify FIFO breadth layers

Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor

Collect Breadth-First Layers

from collections import deque

def breadth_layers(adjacency, start):
    queue = deque([start])
    seen = {start}
    layers = []
    while queue:
        layer = []
        for _ in range(len(queue)):
            node = queue.popleft()
            layer.append(node)
            for neighbor in adjacency[node]:
                if neighbor not in seen:
                    seen.add(neighbor)
                    queue.append(neighbor)
        layers.append(layer)
    return layers

Trace a Fixed Batch in a Growing Queue

Predict whether lowercase items are processed in this batch. The length is captured once before removal begins; it represents exactly the two items already waiting. Each removal adds new work to the right, but those arrivals belong to the next batch. Lines 5–7 form the loop body; compare the final queue with the printed processing order.

Line Python statement Observation
1 from collections import deque Use the established FIFO container.
2 pending = deque(["A", "B"]) Start with two waiting items.
3 batch_size = len(pending) Freeze this batch boundary.
4 for _ in range(batch_size): Run exactly two iterations.
5 item = pending.popleft() Loop body: remove the oldest waiting item.
6 print("process", item) Loop body: observe processing order.
7 pending.append(item.lower()) Loop body: add next-batch work.
8 print(list(pending)) Display the waiting next batch.
9 print(batch_size) Confirm the unchanged boundary.

Expected printed output:

Print Output
1 process A
2 process B
3 ['a', 'b']
4 2

Only A and B are processed. A while pending loop with the same append would keep creating work instead of stopping at this boundary. Traversing a deque directly while changing its size is also the wrong model. Capturing its length costs O(1) and allocates no copy; processing k items with popleft and append costs O(k) queue operations. A list with front removal repeatedly shifts remaining references and can make draining n items O(n squared). The final list(pending) is only an O(n) display snapshot, not part of the batch rule. For breadth-first reasoning, explain what enters the next layer and why it must wait.

Implement a Circular Buffer

A fixed-capacity queue can reuse an array with head, tail, and size. Enqueue writes at tail and advances modulo capacity; dequeue reads at head and advances the same way. When head equals tail, size distinguishes empty from full. Every accepted operation remains O(1).

Advance a Circular Buffer

Reference
def simulate_circular_buffer(capacity, actions):
    storage = [None] * capacity
    head = tail = size = 0
    output = []
    for action in actions:
        if action[0] == 'put':
            if size < capacity:
                storage[tail] = action[1]
                tail = (tail + 1) % capacity
                size += 1
        elif size == 0:
            output.append(None)
        else:
            output.append(storage[head])
            head = (head + 1) % capacity
            size -= 1
    return output
Practice

Implement simulate_circular_buffer(capacity, actions). Accept puts while space remains and return values or None for each get in FIFO order. capacity is a nonnegative integer; every action is either ('put', value) or ('get',).

Public tests

  • Verify FIFO wraparound behavior

Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor

Advance a Circular Buffer

def simulate_circular_buffer(capacity, actions):
    storage = [None] * capacity
    head = tail = size = 0
    output = []
    for action in actions:
        if action[0] == 'put':
            if size < capacity:
                storage[tail] = action[1]
                tail = (tail + 1) % capacity
                size += 1
        elif size == 0:
            output.append(None)
        else:
            output.append(storage[head])
            head = (head + 1) % capacity
            size -= 1
    return output

Trace Full Rejection and FIFO Wraparound

The circular Lab rejects a third put into two full slots. A get frees the oldest slot; the next accepted put wraps to it while the other live value keeps its place in FIFO order.

print(simulate_circular_buffer(2, [('put', 4), ('put', 7), ('put', 9), ('get',), ('put', 2), ('get',), ('get',), ('get',)])) followed by print(simulate_circular_buffer(0, [('put', 4), ('get',)]))

Step Executed statement State Why
1 storage = [None] * capacity; head = tail = size = 0 storage = [None, None]; head = tail = 0; size = 0 Size distinguishes empty state from coinciding indices.
2 storage[tail] = action[1]; tail = (tail + 1) % capacity; size += 1 after puts 4, 7: storage = [4, 7]; head = tail = 0; size = 2 Two accepted writes fill storage and wrap tail.
3 if size < capacity: put 9 rejected; storage = [4, 7]; size = 2 The contract preserves live values rather than evicting one.
4 output.append(storage[head]); head = (head + 1) % capacity; size -= 1 output = [4]; head = 1; tail = 0; size = 1 The oldest slot becomes available.
5 storage[tail] = action[1]; tail = (tail + 1) % capacity; size += 1 after put 2: storage = [2, 7]; head = tail = 1; size = 2 Logical order remains 7 then 2 despite physical order.
6 output.append(storage[head]); head = (head + 1) % capacity; size -= 1 get 7: output = [4, 7]; head = 0; tail = 1; size = 1 The next oldest slot is removed, and head wraps while 2 remains live.
7 output.append(storage[head]); head = (head + 1) % capacity; size -= 1 get 2: output = [4, 7, 2]; head = tail = 1; size = 0 Removing the last live value restores empty state without clearing physical storage.
8 output.append(None) empty get: output = [4, 7, 2, None]; head = tail = 1; size = 0 The size-zero branch does not dereference storage or advance the indices.
Print Output
1 [4, 7, 2, None]
2 [None]

Equal head and tail indices can mean either full or empty. size distinguishes them. Physical slot order can differ from logical FIFO order after wrapping.

Choose Queue or Another Frontier

Use a queue when arrival or graph distance determines processing order. Use a stack for nested or depth-first work, a priority queue when the smallest key must leave first, and a deque when both ends are meaningful. Sorting all pending work repeatedly is not a substitute for a priority queue.

FIFO and Circular State Mistakes

  • Using list.pop(0) hides O(n) shifting inside every dequeue.
  • Marking nodes seen at removal allows multiple parents to enqueue duplicates.
  • Iterating directly over a growing queue blurs the current and next breadth layers.
  • A circular buffer with only head and tail cannot distinguish full from empty without another rule.

Explain It in an Interview

Define what one queued item represents and why FIFO order matches the problem’s guarantee. State when items become seen, what is true before a dequeue, and whether the maximum frontier controls space. For a circular buffer, explain the meaning of all three counters before writing modulo arithmetic.

Advance a Circular Buffer(opens in a new tab) isolates wraparound state. Design Circular Queue(opens in a new tab) adds the full public API and persistent empty/full semantics.

Python Version Note

Complexity & Invariants

Interview bounds depend on the stated representation, input model, and real Python operations.

OperationAverageWorstInterview note
Deque enqueue or dequeueO(1)O(1)Constant extra working space per operation; stored frontier needs O(f) space for f pending items.
Circular command streamO(c + a)O(c + a)Initialize capacity c slots and process a actions; includes returned get results. Zero capacity accepts no puts.
Collect BFS layersO(V + E)O(V * (V + E))V reachable vertices and E examined neighbor entries; expected linear traversal uses ordinary hashing. Collision-heavy seen checks can degrade the worst case.

Space

O(1) for deque enqueue or dequeue; O(c + a) for circular command stream. BFS uses O(V) visited, frontier and returned layers, excluding input adjacency.

Assumptions

  • Constant extra working space per operation; stored frontier needs O(f) space for f pending items.
  • Initialize capacity c slots and process a actions; includes returned get results. Zero capacity accepts no puts.

Invariants Worth Saying Aloud

  1. The front names the oldest pending item; new work enters at the back.
  2. Freeze the current queue length before processing one breadth layer.
  3. head identifies the oldest live slot, tail the next write slot, and 0 <= size <= capacity.

When To Use Or Avoid Queue

Use It When

  • Use deque append/popleft for an unbounded FIFO frontier.
  • Use circular indices when bounded queue storage is part of the problem.

Choose Another Tool When

  • Use a stack for newest unfinished work or a heap for priority order.
  • Do not substitute automatic eviction for full-put rejection.

Common Pitfalls

These are the mistakes most likely to survive a happy-path example and fail a boundary case.

Removing the newest value from a FIFO

Right-end pop reverses arrival order even though it succeeds.

Prevent it: Use append for arrival and popleft for oldest-first removal.

Avoid

value = pending.pop()

Use instead

value = pending.popleft()

Evicting when a full put must be rejected

maxlen append discards the oldest value, whereas the circular Lab rejects a full put.

Prevent it: Check capacity before insertion under a rejection contract.

Avoid

pending.append(value)

Use instead

if len(pending) < capacity:
    pending.append(value)

Advancing a circular index without wrapping

The index after the final slot is invalid; the next physical slot must be zero.

Prevent it: Use modulo positive capacity on accepted index advances.

Avoid

value = storage[head]
head += 1
next_value = storage[head]

Use instead

value = storage[head]
head = (head + 1) % capacity
next_value = storage[head]

Reviewed References

Official Python documentation supports language behavior. Canonical problem pages provide additional practice context.