M09 · Queues and Deques

Queues: First In, First Out in a Ring Buffer

A queue serves elements in the order they arrived. Removing from the front of a plain array would shift everything, so a queue keeps a moving head index and lets the indices wrap around the end of a fixed array. Nothing ever moves, and both operations are constant time.

~35 minBeginnerC# · Python · Java · C++
Curriculum: M09 Queues and Deques · 1 of 1 lessons available

You will be able to

  • Describe FIFO order and predict the output of any sequence of enqueue, dequeue and peek.
  • Explain why dequeuing from the front of a plain array is O(n) and how a ring buffer avoids it.
  • Compute the tail slot as (head + count) mod capacity and trace wraparound slot by slot.
  • Tell a full ring buffer from an empty one, and handle overflow and underflow explicitly.
  • Choose the right queue or deque type in C#, Python, Java and C++ and read their empty and full behaviour correctly.

Helpful before this lesson

  • M05 Arrays — Contiguous storage, index arithmetic, and how a dynamic array grows while keeping append cheap.
  • M08 Stacks — Last in, first out: implementations, expression handling and the monotonic stack.

Guidance only. Those modules are planned; the essentials are recapped here.

Visual walkthrough

The interactive visualizer needs JavaScript. The explanation and all four implementations below work without it.

Mental model

A queue is a line at a counter: people join at the back and are served from the front. The first to arrive is the first to leave, first in, first out (FIFO). The operations:

  • enqueue(x): add x at the back (the tail).
  • dequeue(): remove and return the element at the front (the head).
  • peek(): return the front element without removing it.

Queues appear wherever work must be handled in arrival order: print jobs, network packets, messages between threads, and breadth-first search, which explores a graph or tree level by level because it takes nodes out in the order it found them.

Why not a plain array?

A stack works on one end of an array, which is cheap. A queue needs both ends: add at one, remove at the other. Put the front at index 0 and every dequeue must shift all remaining elements one slot left, which is O(n). Put the front at the end instead and enqueue becomes the expensive one.

A first fix: leave the elements where they are and keep a head index that moves right on every dequeue. Dequeue is now O(1), but the slots behind head are never reused. After enough traffic the tail reaches the end of the array while the front is empty: the queue looks full while holding almost nothing.

The ring buffer

The real fix is to let indices wrap around. Treat the array as a circle: the slot after capacity - 1 is slot 0. The queue stores three things:

  • slots: a fixed array of capacity cells.
  • head: the index of the front element.
  • count: how many elements the queue holds.

The tail, where the next element goes, is not stored; it is computed:

tail = (head + count) mod capacity

The operations:

enqueue(x):
    if count == capacity: fail with overflow
    slots[(head + count) mod capacity] = x
    count += 1

dequeue():
    if count == 0: fail with underflow
    x = slots[head]
    slots[head] = empty          # drop the reference
    head = (head + 1) mod capacity
    count -= 1
    return x

Nothing shifts. Each operation is a handful of arithmetic steps and one read or write: O(1), worst case, not merely amortized.

Run the Wraparound preset (capacity 4). Enqueue 10, 20, 30 fills slots 0, 1, 2. Two dequeues return 10 and 20 and move head to 2. Now enqueue 40 goes to slot (2 + 1) mod 4 = 3, enqueue 50 to (2 + 2) mod 4 = 0, and enqueue 60 to (2 + 3) mod 4 = 1. The queue is full again, its elements in slots 3, 0, 1 and 2, but in FIFO order they read 30, 40, 50, 60 starting from head. The last dequeue returns 30 and head moves to 3.

Full or empty?

When head and the tail index are equal, the buffer is either completely empty or completely full; the indices alone cannot tell which. There are two common answers:

  • Store count (this implementation). Empty is count == 0, full is count == capacity.
  • Store head and tail and leave one slot unused. Empty is head == tail, full is (tail + 1) mod capacity == head. The buffer holds at most capacity - 1 elements, but no counter is needed, which suits lock-free single-producer, single-consumer buffers.

Overflow and underflow

This queue has a fixed capacity on purpose, so it can show both failure modes. Run Overflow and underflow (capacity 2): the third enqueue is rejected, and the third dequeue finds nothing.

Teaching version: full Teaching version: empty
C# InvalidOperationException InvalidOperationException
Python IndexError IndexError
Java IllegalStateException NoSuchElementException
C++ std::overflow_error std::underflow_error

A general-purpose queue grows instead of overflowing. When the buffer is full it allocates a bigger array and copies the elements across in queue order, starting at head and wrapping, into slots 0 … count − 1, then sets head = 0. Copying the raw array as-is would scramble the order. With geometric growth, enqueue is then amortized O(1), exactly like appending to a dynamic array.

Costs

Operation Fixed ring buffer Growable ring buffer
enqueue O(1), or overflow amortized O(1); O(n) on the enqueue that grows
dequeue, peek O(1) O(1)
size, isEmpty, isFull O(1) O(1)
space exactly capacity slots O(n) plus spare capacity

Invariants

  • 0 ≤ count ≤ capacity and 0 ≤ head < capacity.
  • The elements, front to back, are in slots head, head + 1, …, head + count − 1, each taken mod capacity.
  • Every other slot is empty (cleared on dequeue), so the queue never keeps a reference to an element it has handed out.

Deques: both ends

A deque (double-ended queue, pronounced "deck") allows adding and removing at both ends. The same ring buffer supports it: adding at the front moves head back one slot first.

push_front(x):
    if count == capacity: fail or grow
    head = (head - 1 + capacity) mod capacity
    slots[head] = x
    count += 1

The + capacity matters. In C#, Java and C++, % keeps the sign of the left operand, so -1 % 4 is -1, not 3. Python's % already returns a non-negative result for a positive divisor. A deque can act as a stack (one end) or as a queue (both ends), which is why several languages ship one type for both.

Built-in queues and deques

C# Python Java C++
Queue type Queue<T> collections.deque ArrayDeque<E> through Queue std::queue<T> (adaptor)
Enqueue Enqueue(x) append(x) offer(x) / add(x) push(x) / emplace(...)
Dequeue Dequeue() popleft() poll() / remove() front(), then pop() (void)
Peek Peek() d[0] peek() / element() front()
Empty behaviour throws InvalidOperationException; TryDequeue returns false raises IndexError poll/peek return null; remove/element throw undefined behaviour
Deque LinkedList<T> is the usual choice deque itself ArrayDeque, LinkedList std::deque

Details that matter:

  • C# documents Queue<T> as a circular array that grows by reallocating when full. Enqueue is O(1) unless it must grow, then O(n).
  • Python: never use list.pop(0) as a queue; it shifts every element and is O(n). deque gives O(1) appends and pops at both ends. deque(maxlen=n) is bounded, but when full it discards an item from the opposite end instead of failing, which makes it a convenient "last n items" buffer. queue.Queue is the thread-safe queue for producer/consumer code.
  • Java's Queue interface has two method families: add, remove, element throw on failure; offer, poll, peek return false or null. ArrayDeque is a growable circular array and rejects null elements. ArrayBlockingQueue is a fixed-capacity ring buffer like the teaching version: offer returns false when full, add throws IllegalStateException, and put waits for space.
  • C++ std::queue adapts std::deque by default (std::list also works). std::deque is not a ring buffer: it is a sequence of fixed-size blocks indexed by a small map, which gives constant-time pushes and pops at both ends and keeps references to existing elements valid when you push at either end. The standard library has no fixed-capacity ring buffer.

The teaching implementation

The four listings are one design: a fixed array, head and count, the tail computed with modulo, and explicit checks for full and empty. C#, Java and Python clear the slot on dequeue so the garbage collector can reclaim the element. The C++ version moves the element out of the slot instead; the slot keeps a moved-from object until it is overwritten, and because the slots are a std::vector<T> created up front, T must be default-constructible. The listings are checked against one shared fixture of enqueue and dequeue sequences, including wraparound, a full queue and an empty queue.

Common mistakes

  • Dequeuing from the front of a dynamic array (list.pop(0), List<T>.RemoveAt(0), ArrayList.remove(0), vector.erase(begin())): O(n) per call, O(n²) for a whole workload.
  • Forgetting to wrap: computing the tail as head + count without mod capacity writes past the end.
  • Negative modulo when moving head backwards in C#, Java or C++.
  • Confusing full with empty when only head and tail are stored.
  • Growing by copying the raw array: the elements must be laid out again starting at head.
  • Ignoring Java's null returns from poll and peek on an empty queue.

Edge cases

  • Capacity 1: the queue alternates between full and empty; head stays 0 because (0 + 1) mod 1 = 0.
  • Dequeue the element in the last slot: head wraps to 0.
  • Enqueue into a full queue: rejected; the contents are unchanged.
  • Dequeue or peek on an empty queue: rejected.
  • After the queue empties, head can be anywhere; that is fine, because only count decides emptiness.

Worked practice

1. Capacity 5, starting empty: enqueue 1, 2, 3, 4; dequeue twice; enqueue 5, 6, 7. Where is each element, and what is head?

Answer

After the four enqueues: slots 0–3 hold 1–4, head = 0, count = 4. Two dequeues return 1 and 2; head = 2, count = 2. Enqueue 5 goes to (2 + 2) mod 5 = 4, 6 to (2 + 3) mod 5 = 0, 7 to (2 + 4) mod 5 = 1. Final slots: [6, 7, 3, 4, 5], head = 2, count = 5 (full). Front to back: 3, 4, 5, 6, 7.

2. The buffer in question 1 must grow to capacity 10. What does the new array look like?

Answer

Copy in queue order from head: [3, 4, 5, 6, 7, _, _, _, _, _] with head = 0. Copying slot by slot instead ([6, 7, 3, 4, 5, _, …] with head = 2) breaks the queue at once: reading count = 5 slots from head now gives 3, 4, 5 and two empty slots, because 6 and 7 no longer sit right after 5 on the circle.

3. Why does breadth-first search need a queue, not a stack?

Answer

BFS must finish all nodes at distance d before any node at distance d + 1. Nodes are discovered in order of distance, and a FIFO queue hands them back in the same order. A stack would return the most recently discovered node first and the search would go deep instead: that is depth-first search.

4. How can two stacks implement a queue with amortized O(1) operations?

Answer

Push enqueued items onto an in stack. To dequeue, pop from an out stack; if out is empty, first pop everything from in and push it onto out, which reverses the order so the oldest item is on top. Each element moves from in to out at most once, so n operations cost O(n) in total, even though a single dequeue can cost O(n).

Summary

  • A queue is FIFO: enqueue at the tail, dequeue at the head.
  • A ring buffer stores head and count and wraps indices with modulo, so nothing ever shifts and both operations are O(1).
  • Full and empty look the same by indices alone; store a count or sacrifice one slot.
  • Growing a ring buffer means copying the elements in queue order, not the raw array.
  • Built-ins: Queue<T>, collections.deque, ArrayDeque, std::queue over std::deque. Mind Java's null returns and C++'s unchecked front().

Full implementation

The ring-buffer queue in four languages, checked against one shared fixture of enqueue and dequeue sequences, including wraparound, a full queue and an empty queue.

namespace Bekadan.Dsa.Examples.StacksQueues;
 
/// <summary>
/// A FIFO queue in a fixed-size ring buffer: O(1) enqueue and dequeue, no
/// shifting. Indices wrap around with modulo; a full queue rejects new items.
/// </summary>
public sealed class CircularQueue<T>
{
    private readonly T[] _slots;
    private int _head;
    private int _count;
 
    public CircularQueue(int capacity)
    {
        ArgumentOutOfRangeException.ThrowIfLessThan(capacity, 1);
        _slots = new T[capacity];
    }
 
    public int Count => _count;
 
    public IEnumerable<T> FrontToBack()
    {
        for (int i = 0; i < _count; i++)
            yield return _slots[(_head + i) % _slots.Length];
    }
 
    public void Enqueue(T item)
    {
        if (_count == _slots.Length)
            throw new InvalidOperationException("The queue is full.");
        _slots[(_head + _count) % _slots.Length] = item; // the tail wraps to slot 0 after the last slot
        _count++;
    }
 
    public T Dequeue()
    {
        if (_count == 0)
            throw new InvalidOperationException("The queue is empty.");
        T item = _slots[_head];
        _slots[_head] = default!;
        _head = (_head + 1) % _slots.Length;
        _count--;
        return item;
    }
 
    public T Peek()
    {
        if (_count == 0)
            throw new InvalidOperationException("The queue is empty.");
        return _slots[_head];
    }
}

Tested on .NET 10 (SDK 10.0.403), C# 14 · examples/csharp/Bekadan.Dsa.Examples/StacksQueues/CircularQueue.cs

"""A fixed-capacity circular queue (ring buffer)."""
 
from typing import Generic, TypeVar
 
T = TypeVar("T")
 
 
class CircularQueue(Generic[T]):
    """FIFO in a fixed-size ring buffer: O(1) enqueue and dequeue, nothing shifts."""
 
    def __init__(self, capacity: int) -> None:
        if capacity < 1:
            raise ValueError("capacity must be at least 1")
        self._slots: list[T | None] = [None] * capacity
        self._head = 0
        self._count = 0
 
    def __len__(self) -> int:
        return self._count
 
    def front_to_back(self) -> list[T]:
        capacity = len(self._slots)
        return [self._slots[(self._head + i) % capacity] for i in range(self._count)]  # type: ignore[misc]
 
    def enqueue(self, item: T) -> None:
        if self._count == len(self._slots):
            raise IndexError("enqueue on a full queue")
        self._slots[(self._head + self._count) % len(self._slots)] = item  # the tail wraps to slot 0
        self._count += 1
 
    def dequeue(self) -> T:
        if self._count == 0:
            raise IndexError("dequeue from an empty queue")
        item = self._slots[self._head]
        self._slots[self._head] = None
        self._head = (self._head + 1) % len(self._slots)
        self._count -= 1
        return item  # type: ignore[return-value]
 
    def peek(self) -> T:
        if self._count == 0:
            raise IndexError("peek at an empty queue")
        return self._slots[self._head]  # type: ignore[return-value]

Tested on CPython 3.14.0 · examples/python/dsa_examples/circular_queue.py

package dev.bekadan.dsa.stacks;
 
import java.util.ArrayList;
import java.util.List;
import java.util.NoSuchElementException;
 
/** A FIFO queue in a fixed-size ring buffer: O(1) enqueue and dequeue, nothing shifts. */
public final class CircularQueue<T> {
    private final Object[] slots;
    private int head;
    private int count;
 
    public CircularQueue(int capacity) {
        if (capacity < 1) {
            throw new IllegalArgumentException("capacity must be at least 1");
        }
        slots = new Object[capacity];
    }
 
    public int size() {
        return count;
    }
 
    @SuppressWarnings("unchecked") // only T values are ever stored
    private T at(int index) {
        return (T) slots[index];
    }
 
    public List<T> frontToBack() {
        List<T> result = new ArrayList<>();
        for (int i = 0; i < count; i++) {
            result.add(at((head + i) % slots.length));
        }
        return result;
    }
 
    public void enqueue(T item) {
        if (count == slots.length) {
            throw new IllegalStateException("The queue is full.");
        }
        slots[(head + count) % slots.length] = item; // the tail wraps to slot 0 after the last slot
        count++;
    }
 
    public T dequeue() {
        if (count == 0) {
            throw new NoSuchElementException("The queue is empty.");
        }
        T item = at(head);
        slots[head] = null;
        head = (head + 1) % slots.length;
        count--;
        return item;
    }
 
    public T peek() {
        if (count == 0) {
            throw new NoSuchElementException("The queue is empty.");
        }
        return at(head);
    }
}

Tested on Java 25 (Temurin 25.0.5); also compiles on Java 17 · examples/java/src/main/java/dev/bekadan/dsa/stacks/CircularQueue.java

#pragma once
 
#include <cstddef>
#include <stdexcept>
#include <utility>
#include <vector>
 
namespace bekadan::dsa {
 
// A FIFO queue in a fixed-size ring buffer: O(1) enqueue and dequeue, nothing
// shifts. Indices wrap around with modulo; a full queue rejects new items.
template <typename T>
class CircularQueue {
public:
    explicit CircularQueue(std::size_t capacity) : slots_(capacity) {
        if (capacity == 0) throw std::invalid_argument("capacity must be at least 1");
    }
 
    [[nodiscard]] std::size_t size() const noexcept { return count_; }
 
    [[nodiscard]] std::vector<T> front_to_back() const {
        std::vector<T> result;
        for (std::size_t i = 0; i < count_; ++i) result.push_back(slots_[(head_ + i) % slots_.size()]);
        return result;
    }
 
    void enqueue(T item) {
        if (count_ == slots_.size())
            throw std::overflow_error("enqueue on a full queue");
        slots_[(head_ + count_) % slots_.size()] = std::move(item);  // the tail wraps to slot 0
        ++count_;
    }
 
    T dequeue() {
        if (count_ == 0)
            throw std::underflow_error("dequeue from an empty queue");
        T item = std::move(slots_[head_]);
        head_ = (head_ + 1) % slots_.size();
        --count_;
        return item;
    }
 
    [[nodiscard]] const T& peek() const {
        if (count_ == 0)
            throw std::underflow_error("peek at an empty queue");
        return slots_[head_];
    }
 
private:
    std::vector<T> slots_;
    std::size_t head_ = 0;
    std::size_t count_ = 0;
};
 
}  // namespace bekadan::dsa

Tested on C++23, GCC 15.3 (libstdc++) · examples/cpp/include/bekadan/dsa/circular_queue.hpp

References