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): addxat 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 ofcapacitycells.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 iscount == 0, full iscount == capacity. - Store
headandtailand leave one slot unused. Empty ishead == tail, full is(tail + 1) mod capacity == head. The buffer holds at mostcapacity - 1elements, 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 ≤ capacityand0 ≤ head < capacity.- The elements, front to back, are in slots
head, head + 1, …, head + count − 1, each taken modcapacity. - 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).dequegives 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.Queueis the thread-safe queue for producer/consumer code. - Java's
Queueinterface has two method families:add,remove,elementthrow on failure;offer,poll,peekreturnfalseornull.ArrayDequeis a growable circular array and rejectsnullelements.ArrayBlockingQueueis a fixed-capacity ring buffer like the teaching version:offerreturnsfalsewhen full,addthrowsIllegalStateException, andputwaits for space. - C++
std::queueadaptsstd::dequeby default (std::listalso works).std::dequeis 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 + countwithoutmod capacitywrites past the end. - Negative modulo when moving
headbackwards in C#, Java or C++. - Confusing full with empty when only
headandtailare stored. - Growing by copying the raw array: the elements must be laid out again starting at
head. - Ignoring Java's
nullreturns frompollandpeekon an empty queue.
Edge cases
- Capacity 1: the queue alternates between full and empty;
headstays 0 because(0 + 1) mod 1 = 0. - Dequeue the element in the last slot:
headwraps to 0. - Enqueue into a full queue: rejected; the contents are unchanged.
- Dequeue or peek on an empty queue: rejected.
- After the queue empties,
headcan be anywhere; that is fine, because onlycountdecides 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
headandcountand 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::queueoverstd::deque. Mind Java'snullreturns and C++'s uncheckedfront().