Stack / queue / deque · enqueue/dequeue O(1)

Queue (ring buffer)

Enqueue and dequeue in a fixed array with head, tail and wraparound.

The full explanation, derivation and practice are in the lesson Queues: first in, first out in a ring buffer.

Implementation

The code the visualizer highlights, in four languages. Each is tested against one shared set of cases and a randomized comparison with the language's built-in equivalent.

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