Data structure · Linear structures
Queue and deque
First in, first out. A ring buffer gives O(1) enqueue and dequeue without shifting; a deque adds both ends.
The derivations, edge cases and exercises are in the lesson Queues: first in, first out in a ring buffer. Open it full width in the playground.
On this page
The idea
A queue serves elements in arrival order: enqueue at the tail, dequeue at the head. Removing from the front of a plain array would shift everything, so the head and tail indices move instead and wrap around the end of a fixed buffer.
A deque (double-ended queue) allows push and pop at both ends; the built-ins in all four languages are deques, and a queue is a deque used from two ends.
Representation. A fixed buffer with head index, count and wraparound (tail = (head + count) mod capacity).
Operations
| Operation | Time | Extra space | Notes |
|---|---|---|---|
| Enqueue | O(1) | O(1) | The teaching queue has a fixed capacity and rejects a full enqueue; growable versions are amortized O(1). |
| Dequeue | O(1) | O(1) | Fails on an empty queue. |
| Peek front | O(1) | O(1) | |
| Push / pop at either end (deque) | O(1) amortized | O(1) amortized |
Invariants
What stays true before and after every operation.
- 0 ≤ count ≤ capacity.
- The elements are the count slots starting at head, wrapping past the end of the buffer.
- Dequeue order equals enqueue order.
When to use it
Use it when
- Work must be handled in arrival order: breadth-first search, schedulers, buffering between producer and consumer.
- You need a sliding window that drops old items from one end and adds new ones at the other (deque).
Avoid it when
- The next item should be the most urgent, not the oldest (use a priority queue).
- You need random access by position in the middle.
Built-in equivalents
What the standard library of each language offers. Linked types have a full page in the collections encyclopedia with every operation’s complexity, memory effects and a tested example.
C#
- Enqueue O(1)
- Dequeue O(1)
- Peek / TryPeek O(1)
- TryDequeue O(1)
Python
- append O(1)
- appendleft O(1)
- popleft O(1)
- pop / d[-1] O(1)
Java
C++
- push_back / push_front O(1) (the standard says inserting at either end always takes constant time)
- pop_front / pop_back O(1)
- operator[] / at O(1)
Step through it
The interactive lab for queue and deque: custom and seeded inputs, stepping forward and backward, with the active line highlighted in the code.
Implementation in four languages
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
Learn more
Lessons
- Queues: first in, first out in a ring buffer· M09 Queues and Deques
Algorithms that use it
Problems, patterns and exercises
- PatternBreadth-first search and level order· O(V + E)
- PatternSliding window· O(n)
- PatternTopological ordering· O(V + E)