A queue is a first-in, first-out (FIFO) collection: items join at the back and leave from the front, in arrival order. A deque (double-ended queue) allows adding and removing at both ends. Queues schedule work fairly, buffer data between producers and consumers, and drive breadth-first search. This lesson covers the circular buffer that makes them O(1), the two-stack trick, deques and blocking queues.
Think of it like
A line at a ticket counter
People join at the back of the line and are served from the front. Nobody cuts in, so whoever arrived first is served first. A circular buffer is like a round counter with numbered seats: the server moves around the circle, and new arrivals fill the seats freed behind them instead of everyone shuffling forward.
How it works
| Operation | Also called | Effect | Time |
|---|---|---|---|
enqueue(x) | offer, push, append | Add x at the back | O(1) |
dequeue() | poll, pop, popleft | Remove and return the front item | O(1) |
peek() | front | Return the front item without removing it | O(1) |
isEmpty() / size() | Check the number of items | O(1) |
The interesting part is achieving O(1) at both ends. A plain array makes enqueue cheap (append at the end) but dequeue expensive: removing index 0 shifts every remaining element. Advancing a head index instead avoids shifting but leaves dead space at the front that is never reused. The circular buffer fixes both problems.
The circular buffer
A circular buffer (ring buffer) is a fixed-size array whose end wraps around to its start. It stores the index of the front element (head) and the number of elements (size). The back position is computed, not stored, and every index is taken modulo the capacity.
| Operation | head | size | Slots [0, 1, 2, 3] |
|---|---|---|---|
| start | 0 | 0 | [ _, _, _, _ ] |
| enqueue A, B, C | 0 | 3 | [ A, B, C, _ ] |
| dequeue → A | 1 | 2 | [ _, B, C, _ ] |
| dequeue → B | 2 | 1 | [ _, _, C, _ ] |
| enqueue D | 2 | 2 | [ _, _, C, D ] |
| enqueue E (wraps to slot 0) | 2 | 3 | [ E, _, C, D ] |
| enqueue F | 2 | 4 | [ E, F, C, D ] (full) |
A bounded ring buffer simply rejects (or blocks on) enqueue when full, which is exactly what audio drivers, network cards and logging systems want. A growable one copies its elements in queue order into an array twice as large, resetting head to 0, which keeps enqueue amortized O(1) just like a dynamic array (Arrays & Dynamic Arrays).
Linked-list queues
A singly Linked Lists with both head and tail pointers is also a natural queue: enqueue appends at the tail, dequeue removes the head, both O(1) in the worst case with no resizing. The cost is one allocation and one pointer per element and worse cache behavior, so array-based ring buffers are usually faster.
Deques: both ends open
A deque supports push and pop at the front and the back in O(1). It can act as a stack, a queue, or both at once. A ring buffer implements it directly: pushing at the front decrements head modulo the capacity.
| Language | Queue | Deque | Notes |
|---|---|---|---|
| Python | collections.deque (append, popleft) | collections.deque | A doubly linked list of fixed-size blocks; queue.Queue is the thread-safe version |
| Java | ArrayDeque via Queue (offer, poll, peek) | ArrayDeque via Deque | A resizable ring buffer; does not accept null |
| C++ | std::queue<T> (push, front, pop) | std::deque<T> | std::deque is a segmented array with O(1) indexing |
| JavaScript / TS | No built-in | No built-in | Use an array plus a head index, or a ring buffer class |
- Sliding window maximum: a deque of indices kept in decreasing value order gives each window's maximum in O(1) amortized (Monotonic Stack & Queue).
- 0-1 BFS: push 0-weight edges to the front and 1-weight edges to the back to get shortest paths without a heap.
- Work stealing: thread pools let each worker pop its own deque from one end while idle workers steal from the other end.
- Palindrome checks and undo with a size limit: remove from both ends as needed.
A queue from two stacks
A classic puzzle: build a FIFO queue using only LIFO stacks. Use an in stack for enqueues and an out stack for dequeues. When out is empty and a dequeue arrives, pop everything from in and push it onto out, which reverses the order so the oldest element ends up on top.
| Operation | in (top on right) | out (top on right) | Returns |
|---|---|---|---|
| enqueue 1, 2, 3 | 1, 2, 3 | (empty) | |
| dequeue: out is empty, transfer | (empty) | 3, 2, 1 | 1 |
| enqueue 4 | 4 | 3, 2 | |
| dequeue: out not empty | 4 | 3 | 2 |
| dequeue | 4 | (empty) | 3 |
| dequeue: transfer again | (empty) | (empty) | 4 |
Priority queues: a preview
A priority queue ignores arrival order and always serves the element with the highest priority (or smallest key). Hospital triage, operating-system schedulers and Dijkstra's Algorithm all need one. A sorted array or list would make one of insert or remove O(n); a binary heap makes both O(log n). That structure gets its own lesson: Heaps & Priority Queues.
Queues in breadth-first search
BFS explores a graph in rings: first the source, then all vertices one edge away, then two edges away, and so on. A FIFO queue guarantees that order, because every vertex at distance d is enqueued before any vertex at distance d + 1. That is why BFS finds shortest paths in unweighted graphs (Breadth-First Search).
- 1
Seed
Enqueue the source and mark it visited with distance 0.
- 2
Dequeue
Take the vertex at the front of the queue.
- 3
Expand
For each unvisited neighbor, mark it visited, set its distance to one more than the current vertex, and enqueue it.
- 4
Repeat
Continue until the queue is empty. Every vertex is enqueued and dequeued at most once: O(V + E).
Blocking queues and producer-consumer
In concurrent programs a queue decouples producers (threads that create work) from consumers (threads that process it). A blocking queue makes put wait while the queue is full and take wait while it is empty, so producers cannot outrun consumers and nobody needs to busy-wait.
Bounded queue
- Fixed capacity, often a ring buffer
- Full queue blocks producers: natural backpressure
- Memory use is predictable
- Java
ArrayBlockingQueue, Pythonqueue.Queue(maxsize=n), Go buffered channels
Unbounded queue
- Producers never block
- A slow consumer lets the backlog grow without limit
- Can end in out-of-memory crashes under load
- Java
LinkedBlockingQueue(default), Pythonqueue.Queue()
Scale the same idea across machines and you get message brokers such as Kafka, RabbitMQ and SQS, which buffer work between services, absorb traffic spikes and let consumers retry. See Message Queues & Pub/Sub in the system design track.
Complexity
| Operation | Circular buffer | Linked list | Two stacks |
|---|---|---|---|
| enqueue | O(1) | O(1) | O(1) |
| dequeue | O(1) | O(1) | O(1) |
| peek | O(1) | O(1) | O(1) |
| Worst single dequeue | O(1) | O(1) | O(n) |
| Resize when full | O(n) | N/A | N/A |
Circular-buffer enqueue is amortized O(1) when it grows; two-stack dequeue is amortized O(1) because each element is transferred once. All use O(n) space.
Implementation
A ring buffer that tracks head and size, wraps indices with modulo, and doubles its capacity (unrolling the elements in queue order) when full.
from typing import Generic, Optional, TypeVar, cast
T = TypeVar("T")
class CircularQueue(Generic[T]):
"""FIFO queue on a ring buffer that doubles when full."""
def __init__(self, capacity: int = 4) -> None:
self._data: list[Optional[T]] = [None] * max(1, capacity)
self._head = 0 # index of the front element
self._size = 0
def __len__(self) -> int:
return self._size
def enqueue(self, x: T) -> None: # amortized O(1)
if self._size == len(self._data):
self._grow()
tail = (self._head + self._size) % len(self._data)
self._data[tail] = x
self._size += 1
def dequeue(self) -> T: # O(1)
if self._size == 0:
raise IndexError("dequeue from empty queue")
x = self._data[self._head]
self._data[self._head] = None # drop the reference
self._head = (self._head + 1) % len(self._data) # wrap around
self._size -= 1
return cast(T, x)
def peek(self) -> T:
if self._size == 0:
raise IndexError("peek at empty queue")
return cast(T, self._data[self._head])
def _grow(self) -> None: # O(n): unroll into a bigger array
old = self._data
self._data = [None] * (2 * len(old))
for i in range(self._size):
self._data[i] = old[(self._head + i) % len(old)]
self._head = 0
q = CircularQueue[str](4)
for ch in "ABC":
q.enqueue(ch)
print(q.dequeue(), q.dequeue()) # A B
for ch in "DEFG": # E and F wrap around; G triggers a resize
q.enqueue(ch)
print([q.dequeue() for _ in range(len(q))]) # ['C', 'D', 'E', 'F', 'G']Key takeaways
- A queue is FIFO: enqueue at the back, dequeue from the front, both O(1) with the right implementation.
- A circular buffer reuses freed slots by wrapping indices modulo the capacity; track the size to tell full from empty.
- Deques allow O(1) operations at both ends and power sliding-window maximum, 0-1 BFS and work stealing.
- Two stacks make a queue with amortized O(1) operations because each element is transferred only once.
- BFS relies on FIFO order to visit vertices in increasing distance; priority queues (heaps) serve by priority instead.
- Bounded blocking queues give producer-consumer systems natural backpressure.
Common pitfalls
- Building a queue on
list.pop(0),shift()orArrayList.remove(0), which are O(n) per dequeue. - Confusing full and empty in a ring buffer that stores only head and tail indices.
- Forgetting the modulo when advancing indices, or growing a ring buffer with a plain array copy that breaks queue order.
- Marking BFS vertices visited on dequeue instead of enqueue, which enqueues duplicates.
- Using an unbounded queue between a fast producer and a slow consumer, leading to unbounded memory growth.
Interview tips
- For "implement a queue with stacks", explain the lazy transfer and prove amortized O(1) by counting moves per element.
- For "design a circular queue", state your full/empty convention up front (a size counter is simplest).
- When a problem asks for the minimum number of steps in an unweighted setting, say "BFS with a queue" immediately.
Real-world applications
- Task schedulers, print spoolers and request handling in arrival order.
- Breadth-first search, level-order tree traversal and shortest paths in unweighted graphs.
- Audio, video and network buffers built on ring buffers.
- Producer-consumer pipelines, thread pools and message brokers.
Practice problems
Test yourself
A circular buffer has capacity 8, head = 6 and size = 4. At which index does the next enqueue write?
Related topics
Finished this lesson? Track it to see your progress on the roadmap.