AlgoViz

Queue

easy 15 min

A queue is a linear data structure where items join at the rear and leave from the front.

Chapter mnemonic

Which item leaves next?

Lift the top plate. Serve the first guest. Call the urgent case.

The newest arrival has the most urgent case. Which structure serves them first because of urgency?

A priority queue orders removal by priority.

Video lesson · Chapter 1 of 6

The next shopper

0:00 / 4:07

The queue in 75 seconds

1:22Reel

How it works

Step through the idea, or press Play.

Step 1 of 3

Enqueue at the rear. A new item always joins the back of the line; nobody cuts in

Understand it

Start here

What a queue is

A queue is a linear data structure where items are added at one end, the rear, and removed from the other end, the front. The first item in is the first item out: FIFO, First In, First Out. Think of a line at a ticket counter: the first person to join is the first to be served.

  • FIFO order

    The oldest item always leaves first.

  • Two ends, two jobs

    Insert only at the rear, remove only at the front.

  • Order is preserved

    Enqueue 1, 2, 3 and you dequeue 1, 2, 3. A stack would reverse it.

The picture

FIFO in one picture

The whole life of an item in a queue
  1. 1EnqueueJoin at the rear
  2. 2WaitMove up as others leave
  3. 3PeekReach the front, be seen
  4. 4DequeueLeave from the front

Every item walks the same path, so items leave in the order they arrived.

A queue of four, front to rear

Items enter on the right and exit on the left. Nothing in the middle is ever touched.

The API

Core operations

OperationWhat it doesOn 10, 20, 30, 40
enqueue(x)Adds x at the rearenqueue(50) gives 10, 20, 30, 40, 50
dequeue()Removes and returns the frontreturns 10, leaves 20, 30, 40
peek() / front()Returns the front without removing itreturns 10, queue unchanged
is_empty()True when there is nothing to dequeueFalse
size()Number of items4
The queue is drawn front to rear: 10 has waited longest, 40 arrived last.

Under the hood

How enqueue and dequeue work

enqueue(x)

Only a bounded queue can be full. A deque or linked list simply grows.

dequeue()

peek() follows the same path but stops after reading the value.

Complexity

What each operation costs

Operationcollections.dequePython listWhy
enqueueO(1)O(1)O(1)O(1) amortisedWrites one slot at the rear
dequeueO(1)O(1)O(n)O(n)list.pop(0) shifts every remaining item left
peekO(1)O(1)O(1)O(1)Reads the front directly
is_empty, sizeO(1)O(1)O(1)O(1)The length is tracked as items come and go
searchO(n)O(n)O(n)O(n)Has to walk the line
the queue itselfO(n)O(n) spaceO(n)O(n) spaceOne slot per stored item

Why list.pop(0) ruins a queue

(n−1)+(n−2)+⋯+1⏟shifts to drain n items=n(n−1)2=O(n2)vs1+1+⋯+1⏟deque.popleft=O(n)\underbrace{(n-1) + (n-2) + \dots + 1}_{\text{shifts to drain } n \text{ items}} = \frac{n(n-1)}{2} = O(n^2) \quad\text{vs}\quad \underbrace{1 + 1 + \dots + 1}_{\text{deque.popleft}} = O(n)
Each pop(0) moves everything behind the front. Draining a list-backed queue is quadratic; draining a deque is linear. For BFS that is the difference between O(V+E)O(V + E) and an extra O(V2)O(V^2).

Implementation

Four ways to build one

  • collections.deque

    append to enqueue, popleft to dequeue. Blocks of slots linked together, O(1)O(1) at both ends. The default in Python.

  • Linked list

    Keep head (front) and tail (rear): tail.next = node; tail = node. Never resizes; one pointer per node.

  • Circular array

    A fixed buffer where rear = (rear + 1) % capacity wraps round. Fixed memory, no allocation, can be full.

  • Array plus front index

    Append at the end, move a front index instead of shifting, and compact when half the array is dead space.

Python
from collections import dequequeue = deque()queue.append("Alice")    # enqueuequeue.append("Bob")queue.append("Carol")print(queue[0])          # peek    -> Aliceprint(queue.popleft())   # dequeue -> Aliceprint(len(queue))        # size    -> 2print(not queue)         # is_empty -> False
In Python, a deque is already a queue. Use append and popleft.
Edit and run it in your browser
Python
class Node:    def __init__(self, val):        self.val = val        self.next = Noneclass LinkedQueue:    def __init__(self):        self.head = self.tail = None   # front and rear        self.count = 0    def enqueue(self, val):        node = Node(val)        if self.tail is None:            self.head = self.tail = node        else:            self.tail.next = node      # link after the rear            self.tail = node        self.count += 1    def dequeue(self):        if self.head is None:            raise IndexError("dequeue from empty queue")        val = self.head.val        self.head = self.head.next        if self.head is None:          # queue became empty            self.tail = None        self.count -= 1        return valq = LinkedQueue()for x in (1, 2, 3):    q.enqueue(x)print(q.dequeue(), q.dequeue(), q.count)   # 1 2 1
A linked-list queue: dequeue at the head, enqueue at the tail.
Edit and run it in your browser

Deep dive

The circular buffer

A plain fixed array wastes the slots before the front once items leave. A circular buffer (ring buffer) treats the array as a ring: when the rear reaches the end, it wraps back to slot 0 and reuses freed space. It is modular arithmetic on indexes.

Where the next item goes

tail=(head+count) mod khead′=(head+1) mod k\text{tail} = (\text{head} + \text{count}) \bmod k \qquad \text{head}' = (\text{head} + 1) \bmod k
With capacity k=5k = 5, head =2= 2 and count =3= 3, the next item goes to (2+3) mod 5=0(2 + 3) \bmod 5 = 0: the rear wraps round to the start. Full means count =k= k; empty means count =0= 0.

Enqueue into a ring of capacity k

Tracking count keeps full and empty apart; with only head and tail, both look like head == tail.
Python
class CircularQueue:    def __init__(self, k):        self.buf = [None] * k        self.head = 0        self.count = 0    def enqueue(self, x):        if self.count == len(self.buf):            return False                       # full        self.buf[(self.head + self.count) % len(self.buf)] = x        self.count += 1        return True    def dequeue(self):        if self.count == 0:            return None                        # empty        x = self.buf[self.head]        self.head = (self.head + 1) % len(self.buf)        self.count -= 1        return xcq = CircularQueue(3)print(cq.enqueue(1), cq.enqueue(2), cq.enqueue(3), cq.enqueue(4))  # True True True Falseprint(cq.dequeue())     # 1, frees slot 0print(cq.enqueue(4))    # True: 4 wraps into slot 0print(cq.buf)           # [4, 2, 3]
A circular queue with capacity 3: the rear wraps to slot 0.
Edit and run it in your browser

Comparison

Queue, stack, deque and priority queue

QueueStackDequePriority queue
OrderFIFOLIFOEither endSmallest (or largest) first
InsertRear, O(1)O(1)Top, O(1)O(1)Both ends, O(1)O(1)O(log⁡n)O(\log n)
RemoveFront, O(1)O(1)Top, O(1)O(1)Both ends, O(1)O(1)O(log⁡n)O(\log n)
AnalogyLine at a storeStack of platesLine open at both endsHospital triage
Graph traversalBFSDFS0-1 BFSDijkstra
Typical useScheduling, bufferingUndo, recursionSliding windowTop-k, scheduling by urgency
A deque generalises both a queue and a stack. A priority queue is usually a heap, not a line.

Use a queue when

  • You need first-come, first-served order.
  • You do BFS or level-order traversal.
  • You schedule tasks or process jobs in arrival order.
  • You buffer a data stream between a producer and a consumer.
  • You handle asynchronous requests in order.

Do not use a queue when

  • You need random access by index (use an array).
  • You need LIFO order (use a stack).
  • You search for values often (use a set or dict).
  • You need priority order (use a priority queue).
  • You need both ends equally (use a deque).

Pattern

BFS runs on a queue

The BFS loop

Nodes leave in the order they were discovered, so all of distance dd is visited before any of distance d+1d + 1.
Python
from collections import dequegraph = {"A": ["B", "C"], "B": ["A", "D", "E"], "C": ["A", "E", "F"],         "D": ["B"], "E": ["B", "C"], "F": ["C"]}def levels(start):    seen, queue, out = {start}, deque([start]), []    while queue:        level = []        for _ in range(len(queue)):      # exactly the nodes of this level            node = queue.popleft()            level.append(node)            for nb in graph[node]:                if nb not in seen:                    seen.add(nb)         # mark on enqueue                    queue.append(nb)        out.append(level)    return outprint(levels("A"))   # [['A'], ['B', 'C'], ['D', 'E', 'F']]
Level-order BFS: process one level per pass of the outer loop.
Edit and run it in your browser

In the wild

Where queues run

  • Web servers

    Incoming HTTP requests wait in a queue until a worker thread is free.

  • Print spooler

    Documents print in the order they were sent.

  • Message queues

    RabbitMQ, Amazon SQS and Kafka topics hand messages from producers to consumers.

  • BFS

    Shortest paths, level-order traversal, flood fill, web crawlers.

  • Task schedulers

    Round-robin CPU scheduling and job runners such as Celery re-queue unfinished work.

  • Call centres

    Callers on hold are answered in the order they called.

Producer and consumer with a queue in between

A bounded queue adds backpressure: when it is full the producer blocks or requests are rejected.

Pattern spotting

Spotting a queue problem

Should I use a queue?

  • BFS traversal

    Level-by-level exploration of graphs and trees. Process nodes in the order they were discovered.

  • Multi-source BFS

    Enqueue every source first, then run one BFS. Rotting oranges, walls and gates.

  • Sliding window

    A deque gives O(1)O(1) at both ends; keep it monotonic for window maximum.

  • Task scheduling

    Process in FIFO order and re-enqueue anything unfinished. Round-robin, cooldowns.

Recap

Key takeaways

Key points

  • A queue is FIFO: the first item enqueued is the first dequeued, so order is preserved.
  • Items join at the rear and leave from the front. enqueue, dequeue, peek, is_empty and size are O(1)O(1); search is O(n)O(n); space is O(n)O(n).
  • In Python, use collections.deque with append and popleft. list.pop(0) is O(n)O(n).
  • A circular buffer reuses freed slots with % capacity and tracks a count to tell full from empty.
  • BFS is a queue: oldest discovery first gives level order and shortest paths in unweighted graphs.
  • Underflow is dequeuing from empty; overflow is enqueuing into a full bounded queue.

Sources