Circular Queues
A circular queue treats one fixed array as a ring. When an index runs off the end it wraps back to slot 0, so the space freed by dequeues is used again. Enqueue and dequeue are both O(1), with no shifting and no allocation.
The Space a Linear Queue Throws Away
Build a queue on a plain array with two indices. Enqueue writes at rear and moves it right; dequeue reads at front and moves it right. Both are O(1).
The trouble shows up after a while. front only moves forward, so the slots behind it are never used again. Once rear reaches the end of the array, the queue says it is full even if almost every slot is empty. A 1,000-slot array that has passed 1,000 items through is finished, even with only three items waiting.
Shifting everything left to reclaim the space makes dequeue O(n). That is what Python's list.pop(0) does, and it is why draining a list used as a queue costs O(n²).
A circular queue fixes this without moving anything. When rear reaches the end, it carries on at slot 0, into the space front has already left. The array stays the same size, but the indices go round it forever, which is why the structure is also called a ring buffer or circular buffer.
- A linear queue of capacity n can fail after n enqueues in total, however many were dequeued
- Compacting on every dequeue turns an O(1) operation into O(n)
- In the ring, no item ever moves; only the two indices change
Modulo Does the Wrapping
- Enqueue(x): if
size == capacity, report full. Otherwise writexat(front + size) % capacityand add 1 tosize. - Dequeue(): if
size == 0, report empty. Otherwise read the item atfront, setfront = (front + 1) % capacityand subtract 1 fromsize. - Peek(): if not empty, return the item at
frontwithout changing anything.
Every index moves with the same expression: i = (i + 1) % capacity. Adding 1 to the last index gives capacity, and the remainder turns that into 0.
A typical circular queue implementation keeps front and a size count, and works out the write slot as (front + size) % capacity when it needs it. The code on this page does exactly that. Textbooks often keep a rear index instead; the two designs behave the same.
When the capacity is a power of two, % capacity can be replaced by & (capacity - 1), which avoids a division. Network and audio ring buffers usually pick a power-of-two size for this reason, since they run on every packet or every audio frame.
Another design never wraps the counters at all. head and tail just keep growing, the item count is tail - head, and only the array index is masked: tail & (capacity - 1). With 64-bit counters, overflow is not a practical concern. Linux's kfifo works this way.
- Every operation is O(1) time; the queue uses O(capacity) space from the start
- A dequeued value stays in memory until it is overwritten; clear the slot if it holds a large object
- Integer counters that never wrap need the capacity to be a power of two
Full and Empty Look Identical
With wrapping indices, an empty queue has front == rear: nothing has been added since the last removal. Now fill every slot. rear goes all the way round and lands on front again, so a full queue also has front == rear.
The indices alone cannot tell the two states apart. An implementation that ignores this either overwrites live data or refuses a valid insert. There are three standard fixes.
Keep a count. A size field says it directly: 0 is empty, capacity is full. Every slot is usable. The cost is a third variable that both enqueue and dequeue change, which matters in lock-free code.
Leave one slot unused. Call the queue full when (rear + 1) % capacity == front, so rear never catches up with front. Empty stays front == rear. An array of n slots holds n − 1 items, but the producer only writes rear and the consumer only writes front.
Counters that never wrap. tail - head is the count, so neither state is ambiguous.
| Approach | Empty test | Full test | Cost |
|---|---|---|---|
| Keep a count | size == 0 | size == capacity | One more variable; all slots used |
| Leave one slot unused | front == rear | (rear + 1) % cap == front | One slot lost; no extra state |
| Counters that never wrap | tail == head | tail - head == cap | Wide integers; power-of-two size |
- Exam questions on the one-slot rule usually ask why a queue of size n holds only n − 1 items
- With a count, check full before writing and empty before reading, never after
- Mixing the rules (a count and the one-slot test) wastes a slot for nothing
Terms, operations, and practical uses
Buffer mechanics
- Modulo arithmetic
(i + 1) % capacitymoves an index forward and wraps it from the last slot back to 0. - Wrap-aroundThe write position passes the end of the array and continues at slot 0, reusing freed slots.
- Fixed capacityThe array is allocated once; growing it means copying the items into a new array in queue order.
State tracking
- Empty state
size == 0with a count, orfront == rearunder the one-slot rule. - Full state
size == capacitywith a count, or(rear + 1) % capacity == frontunder the one-slot rule. - Unused slotLeaving one slot empty keeps full and empty distinct without a count, at the cost of one item of capacity.
System applications
- Overwrite modeWhen full, the newest item replaces the oldest, keeping a rolling window of recent data.
- Audio streamingThe audio thread reads from a ring while another thread fills it, so playback does not stall.
- Network packetsNetwork cards and drivers share rings of descriptors for incoming and outgoing packets.
Code in Python, C++ and Java
class CircularQueue:
def __init__(self, k):
self.q = [None] * k
self.k = k
self.front = 0
self.size = 0 # an explicit size makes full and empty distinguishable
def is_empty(self):
return self.size == 0
def is_full(self):
return self.size == self.k
def enqueue(self, val):
if self.is_full():
return False
rear = (self.front + self.size) % self.k # wrap with modulo
self.q[rear] = val
self.size += 1
return True
def dequeue(self):
if self.is_empty():
return False
self.front = (self.front + 1) % self.k # advance, never shift
self.size -= 1
return True
def to_list(self):
return [self.q[(self.front + i) % self.k] for i in range(self.size)]
cq = CircularQueue(4)
for value in 'ABC':
cq.enqueue(value)
cq.dequeue() # A leaves
cq.dequeue() # B leaves; slots 0 and 1 are now reusable
cq.enqueue('D') # goes to slot 3
cq.enqueue('E') # wraps back to slot 0
print('Array physically holds [' + ', '.join(str(v) for v in cq.q) + ']')
print('Queue logically holds [' + ', '.join(cq.to_list()) + ']')#include <iostream>
#include <vector>
#include <string>
using namespace std;
class CircularQueue {
vector<string> q;
int k, front_, size_;
public:
CircularQueue(int cap) : q(cap, "-"), k(cap), front_(0), size_(0) {}
bool isEmpty() const { return size_ == 0; }
bool isFull() const { return size_ == k; }
bool enqueue(const string& val) {
if (isFull()) return false;
int rear = (front_ + size_) % k; // wrap with modulo
q[rear] = val;
size_++;
return true;
}
bool dequeue() {
if (isEmpty()) return false;
front_ = (front_ + 1) % k; // advance, never shift
size_--;
return true;
}
void print() const {
cout << "Array physically holds [";
for (int i = 0; i < k; i++) {
if (i) cout << ", ";
cout << q[i];
}
cout << "]\n";
cout << "Queue logically holds [";
for (int i = 0; i < size_; i++) {
if (i) cout << ", ";
cout << q[(front_ + i) % k];
}
cout << "]\n";
}
};
int main() {
CircularQueue cq(4);
cq.enqueue("A");
cq.enqueue("B");
cq.enqueue("C");
cq.dequeue(); // A leaves
cq.dequeue(); // B leaves
cq.enqueue("D"); // slot 3
cq.enqueue("E"); // wraps to slot 0
cq.print();
}import java.util.StringJoiner;
public class Main {
static class CircularQueue {
private final String[] q;
private final int k;
private int front = 0, size = 0;
CircularQueue(int cap) {
k = cap;
q = new String[cap];
java.util.Arrays.fill(q, "-");
}
boolean isEmpty() { return size == 0; }
boolean isFull() { return size == k; }
boolean enqueue(String val) {
if (isFull()) return false;
int rear = (front + size) % k; // wrap with modulo
q[rear] = val;
size++;
return true;
}
boolean dequeue() {
if (isEmpty()) return false;
front = (front + 1) % k; // advance, never shift
size--;
return true;
}
void print() {
StringJoiner phys = new StringJoiner(", ", "[", "]");
for (String s : q) phys.add(s);
StringJoiner logi = new StringJoiner(", ", "[", "]");
for (int i = 0; i < size; i++) logi.add(q[(front + i) % k]);
System.out.println("Array physically holds " + phys);
System.out.println("Queue logically holds " + logi);
}
}
public static void main(String[] args) {
CircularQueue cq = new CircularQueue(4);
cq.enqueue("A");
cq.enqueue("B");
cq.enqueue("C");
cq.dequeue(); // A leaves
cq.dequeue(); // B leaves
cq.enqueue("D"); // slot 3
cq.enqueue("E"); // wraps to slot 0
cq.print();
}
}Step through it
Running on capacity 4: enqueue A, B, C; dequeue twice; enqueue D, E; then try F and G
Where Ring Buffers Are Used
Most circular queue applications sit in infrastructure code, for four reasons.
Memory is fixed and allocated once. Nothing is allocated while the buffer runs, so there is no sudden pause to grow it. An interrupt handler or an audio callback with a deadline of a few milliseconds cannot afford that pause.
The bound forces a decision. When the buffer fills, the code must block the producer, drop the new item, overwrite the oldest, or return an error. For live audio or video, overwriting the oldest is usually right, because a late frame is worthless.
The data is in one array. Reading it in order is cache-friendly, unlike a linked-list queue that allocates a node per item and follows pointers.
One producer and one consumer need no lock. The producer writes only the tail and the consumer writes only the head, so with the right memory ordering no mutex is needed. This is how data moves between a real-time audio thread and the rest of a program, and between network cards and the kernel.
Familiar examples: keyboard and network input buffers, the CPU scheduler's round-robin ready queue, logs that keep only the last n lines, and the producer-consumer bounded buffer.
- Overwrite-oldest suits streams; block-or-reject suits data that must not be lost
- A single-producer, single-consumer ring is the standard lock-free queue
- If the number of items has no upper bound, use a growable queue instead
Edge Cases and Variants
Capacity 1 works with a count: the single slot is either live or free. With the one-slot rule, a capacity of 1 holds nothing, so that rule needs capacity of at least 2.
Textbook start values. Many C textbooks start with front = rear = -1 and treat -1 as empty. That works, but it adds special cases on the first enqueue and the last dequeue. The count version has none.
A linked-list version keeps a circular linked list with one pointer to the last node, whose next is the first. Enqueue and dequeue are still O(1), and there is no capacity limit, but every item costs an allocation. It is the same ring idea applied to nodes; see circular linked lists.
Double-ended rings. Letting front move backwards with (front - 1 + capacity) % capacity gives a deque on the same array; see deques. Note the + capacity: in C, C++ and Java, -1 % 4 is -1, not 3.
- Negative modulo is the classic bug when an index moves backwards
- Growing a full ring means copying items in queue order into a bigger array, not copying the array as is
- Plain queues explains the FIFO interface the ring implements