Layers of Logic

Foundation 06

Queue

A first-in, first-out collection: new items join the back and leave from the front.

Core3 operations comparedJava · Python · C++

What the structure guarantees

A queue preserves arrival order. That property is why breadth-first search processes every state at distance d before any state at distance d + 1.

How that model appears in code

Use deque in Python, ArrayDeque through the Queue interface in Java, and std::queue in C++. Removing index zero from an array-backed list is not a queue implementation; it shifts the remaining items.

Queue basics

Queue<Integer> queue = new ArrayDeque<>();
queue.add(7);
int front = queue.peek();
int removed = queue.poll();

What gets more expensive as the input grows

OperationCostWhy
Add at backO(1)Only the tail changes.
Peek or remove frontO(1)A queue implementation keeps direct access to the head.
Search the queueO(n)Items may need to be inspected in order.

Choose it for the operations it makes cheap

Good fit

  • Breadth-first search
  • Level-order traversal
  • Scheduling in arrival order

Poor fit

  • Depth-first exploration
  • Random access
  • Priority-based removal

Used by

Breadth-first search modules planned for a later release

Errors that survive a first glance

  1. Do not use Python list.pop(0)

    It shifts every remaining element. deque.popleft performs the intended constant-time operation.

  2. Queue is a Java interface

    Instantiate ArrayDeque and store it in a Queue variable.

  3. A priority queue is a different contract

    It removes by priority, not strictly by arrival time.