Implementing Circular Queue in Data Structure
A Circular Queue is a linear data structure that connects the last position back to the first, forming a circle. This design efficiently reuses the empty spaces left behind after elements are dequeued from a regular (linear) queue.
Why Circular Queue?
In a simple linear queue implemented with a fixed-size array, once elements are dequeued from the front, that space is wasted because new elements can still only be added at the rear, even if there is free space at the beginning. A circular queue solves this by wrapping the rear pointer back to index 0 when it reaches the end.
class CircularQueue:
def __init__(self, capacity):
self.queue = [None] * capacity
self.capacity = capacity
self.front = self.size = 0
self.rear = capacity - 1
def is_full(self):
return self.size == self.capacity
def is_empty(self):
return self.size == 0
def enqueue(self, item):
if self.is_full():
raise OverflowError("Queue is full")
self.rear = (self.rear + 1) % self.capacity
self.queue[self.rear] = item
self.size += 1
def dequeue(self):
if self.is_empty():
raise IndexError("Queue is empty")
item = self.queue[self.front]
self.front = (self.front + 1) % self.capacity
self.size -= 1
return item
Complexity
| Operation | Time |
|---|---|
| Enqueue | O(1) |
| Dequeue | O(1) |
Applications
- CPU scheduling using round-robin algorithms.
- Buffering data streams, such as in audio/video streaming.
- Traffic light control systems that cycle through a fixed sequence.
Watching the Pointers Wrap Around
Tracing the class above with a capacity of 4 shows exactly when the modulo arithmetic kicks in. Initially front = 0, rear = 3 and size = 0.
| Operation | front | rear | size | Array contents |
|---|---|---|---|---|
| enqueue(10) | 0 | 0 | 1 | [10, -, -, -] |
| enqueue(20) | 0 | 1 | 2 | [10, 20, -, -] |
| enqueue(30) | 0 | 2 | 3 | [10, 20, 30, -] |
| dequeue() returns 10 | 1 | 2 | 2 | [x, 20, 30, -] |
| dequeue() returns 20 | 2 | 2 | 1 | [x, x, 30, -] |
| enqueue(40) | 2 | 3 | 2 | [x, x, 30, 40] |
| enqueue(50) | 2 | 0 | 3 | [50, x, 30, 40] |
| enqueue(60) | 2 | 1 | 4 | [50, 60, 30, 40] |
After enqueuing 50, rear jumps from 3 back to 0 and reuses a freed slot. A linear queue would have reported "full" at that point even though two cells were empty. A further enqueue now raises an overflow error because size equals capacity.
Version Without a Size Counter
Many textbooks and interviews skip the size variable. The problem is that front == rear could then mean either empty or full. The usual fix is to keep one slot permanently unused, so the queue is full when advancing rear would land on front.
class RingBuffer:
def __init__(self, capacity):
self.data = [None] * (capacity + 1) # one slot always stays free
self.front = 0 # index of the first item
self.rear = 0 # index of the next free slot
def is_empty(self):
return self.front == self.rear
def is_full(self):
return (self.rear + 1) % len(self.data) == self.front
def enqueue(self, item):
if self.is_full():
raise OverflowError("Queue is full")
self.data[self.rear] = item
self.rear = (self.rear + 1) % len(self.data)
def dequeue(self):
if self.is_empty():
raise IndexError("Queue is empty")
item = self.data[self.front]
self.data[self.front] = None # release the reference
self.front = (self.front + 1) % len(self.data)
return item
def peek(self):
if self.is_empty():
raise IndexError("Queue is empty")
return self.data[self.front]
def __len__(self):
return (self.rear - self.front) % len(self.data)
The length formula works even after wrapping, because Python's modulo always returns a non-negative result.
Built-in Alternatives and When to Use Them
In everyday Python, collections.deque(maxlen=n) gives you a bounded queue with fast operations at both ends. Note the behaviour difference: when a full deque receives a new item, it silently drops the oldest one instead of raising an error. That suits "keep the last n readings" use cases, such as a moving average, but not a job queue where losing work is unacceptable. For queues shared between threads, use queue.Queue(maxsize=n), which blocks producers when it fills up.
Bugs to Check For
- Writing
rear + 1without% capacity, which causes an index error at the end of the array. - Relying on
front == rearalone to detect both empty and full states. - Starting
rearat 0 in the size-counter version, which makes the first item land at index 1. - Not clearing dequeued slots in languages with garbage collection, so large objects stay in memory longer than needed.
- Forgetting to test the wrap: always include a sequence of enqueue, dequeue, enqueue that crosses the array's end.