Queues: enqueue, dequeue; circular buffer
A queue adds at the back and removes at the front: first in, first out. A circular buffer reuses its slots as head and tail wrap around.
The idea
At a ticket counter, Ana arrived first and is served first. Newcomers join at the back of the line.
A queue is a container with the same rule: first in, first out (FIFO). Print jobs, network packets and breadth-first search all wait in queues.
Intuition
enqueue adds a value at the rear, called tail. dequeue removes the oldest value at the front, called head.
In a plain array, dequeue removes cell 0 and shifts every other value left. That costs n moves per dequeue.
The front of the queue has to be at index 0 if nothing else tracks it. Shifting keeps it there, at the price of touching every value.
A circular buffer keeps two indices instead: head marks the oldest value, tail the next free slot. Values never move.
When an index passes the last slot it wraps to slot 0, so slots freed at the front are reused. That is why it is also called a ring buffer.
Complexity
enqueue and dequeue on a ring buffer take O(1) time. Shifting a plain array makes each dequeue O(n).
Each ring operation writes or reads one slot and moves one index with a modulo. The queue length never enters the cost.
Space is O(capacity). The ring reserves all its slots up front, even while it holds only a few values.
A growable ring copies its values into a larger array when it fills up, like a dynamic array. Each copy is O(n), but it happens rarely.
Pitfalls
Full: four values in four slots. tail has wrapped all the way around, so head = tail = 0.
Empty also has head = tail. Keep a count (or leave one slot unused) to tell full from empty.
Testing head = tail alone would call a full queue empty and lose every value. The count settles it: 0 means empty and capacity means full.
Variations
A deque allows adds and removes at both ends. A ring buffer supports it by moving head backwards, wrapping 0 to the last slot.
Breadth-first search keeps found but unvisited nodes in a queue, so it visits them in the order it found them.
A linked queue keeps head and tail pointers on a singly linked list. It never fills up, but each value costs a node.
Code
Pseudocode
data ← array of capacity slots, head ← 0, tail ← 0, count ← 0
enqueue(x):
if count = capacity: error "full"
data[tail] ← x
tail ← (tail + 1) mod capacity, count ← count + 1
dequeue():
if count = 0: error "empty"
x ← data[head]
head ← (head + 1) mod capacity, count ← count - 1
return x
front():
if count = 0: error "empty"
return data[head]
rear():
return data[(tail - 1 + capacity) mod capacity]
Python
class RingQueue:
def __init__(self, capacity):
self.data = [None] * capacity
self.head = self.tail = self.count = 0
def enqueue(self, x):
if self.count == len(self.data):
raise OverflowError("queue is full")
self.data[self.tail] = x
self.tail = (self.tail + 1) % len(self.data)
self.count += 1
def dequeue(self):
if self.count == 0:
raise IndexError("queue is empty")
x = self.data[self.head]
self.head = (self.head + 1) % len(self.data)
self.count -= 1
return x
def front(self):
if self.count == 0:
raise IndexError("queue is empty")
return self.data[self.head]
def rear(self):
k = len(self.data)
return self.data[(self.tail - 1 + k) % k]
JavaScript
class RingQueue {
constructor(capacity) {
this.data = new Array(capacity).fill(null);
this.head = this.tail = this.count = 0;
}
enqueue(x) {
if (this.count === this.data.length) throw new Error("queue is full");
this.data[this.tail] = x;
this.tail = (this.tail + 1) % this.data.length;
this.count++;
}
dequeue() {
if (this.count === 0) throw new Error("queue is empty");
const x = this.data[this.head];
this.head = (this.head + 1) % this.data.length;
this.count--;
return x;
}
front() {
if (this.count === 0) throw new Error("queue is empty");
return this.data[this.head];
}
rear() {
const k = this.data.length;
return this.data[(this.tail - 1 + k) % k];
}
}
Java
class RingQueue {
private final int[] data;
private int head = 0, tail = 0, count = 0;
RingQueue(int capacity) { data = new int[capacity]; }
void enqueue(int x) {
if (count == data.length) throw new IllegalStateException("queue is full");
data[tail] = x;
tail = (tail + 1) % data.length;
count++;
}
int dequeue() {
if (count == 0) throw new IllegalStateException("queue is empty");
int x = data[head];
head = (head + 1) % data.length;
count--;
return x;
}
int front() {
if (count == 0) throw new IllegalStateException("queue is empty");
return data[head];
}
int rear() {
return data[(tail - 1 + data.length) % data.length];
}
}
Cost at a glance
| Access | O(1) front / O(n) |
|---|---|
| Search | O(n) |
| Insert | O(1) enqueue |
| Delete | O(1) dequeue |
| Space | O(n) |
Practice problems (6)
Which value leaves first? Warm-up
Start with an empty queue. Run enqueue A, enqueue B, enqueue C, dequeue, enqueue D. Then dequeue until the queue is empty. In which order do the values come out of those last dequeues?
Predict head and tail Warm-up
A circular queue has 4 slots, numbered 0 to 3. Follow enqueue 1, enqueue 2, enqueue 3, dequeue, dequeue, enqueue 4, enqueue 5, dequeue and predict where head and tail land. head is the slot of the oldest value; tail is the next free slot.
Implement a circular queue Standard
Complete CircularQueue, a queue of at most k values stored in a fixed array whose indices wrap around. Every operation must be O(1); do not shift values.
enqueue(x)adds x at the rear and returns true, or returns false when the queue is full.dequeue()removes and returns the front value, or -1 when empty.front()andrear()return the oldest and newest value, or -1 when empty.
The given circularQueue(k, ops) collects one result per operation (enqueue: 1 or 0).
Number of recent calls Standard
A server receives calls at the times in times (milliseconds, strictly increasing). For each call at time t, report how many calls happened in the window [t - 3000, t], including this one.
Return the list of counts, one per call.
Spot the bug: the tail runs off the end Standard
This circular queue works until the tail reaches the last slot. After that, enqueue writes outside the array and rear returns the wrong value. Click the line with the bug, then fix it. Results follow the rules of "Implement a circular queue".
Moving average from a stream Challenge
Numbers arrive one at a time in values. After each number, report the average of the last size numbers (or of all numbers so far, while fewer than size have arrived).
Return the list of averages. Each update must take O(1) time, so do not re-add the whole window.
Related topics
Next on the path: Hash functions: from key to bucket index