Sub topic 10
Circular Queues: Wrap-Around and Full/Empty Conditions
Assume you know arrays, indexing, loops, and Big-O notation. A circular queue is a queue implemented with a fixed-size array. It follows FIFO order: the first element inserted is the first element removed.
Why a circular queue is needed
In a normal array queue, repeated dequeues can leave unused cells at the beginning. Moving every remaining element is costly. A circular queue reuses those cells by wrapping the next position back to index 0.
For an array of capacity n, positions advance with:
next_index = (current_index + 1) % nThe modulo operation produces a value from 0 through n - 1.
A circular queue commonly stores:
front: index of the first elementsize: number of elements currently storedcapacity: length of the array
The rear position is computed as:
rear = (front + size) % capacityThis points to the next free position, not the last occupied position.
Enqueue, dequeue, full, and empty
The queue is empty when size == 0. It is full when size == capacity. Tracking size distinguishes these states even when front and the rear position are equal.
class CircularQueue:
def __init__(self, capacity):
if capacity <= 0:
raise ValueError("capacity must be positive")
self.data = [None] * capacity
self.front = 0
self.size = 0
def enqueue(self, value):
if self.size == len(self.data):
raise OverflowError("queue is full")
rear = (self.front + self.size) % len(self.data)
self.data[rear] = value
self.size += 1
def dequeue(self):
if self.size == 0:
raise IndexError("queue is empty")
value = self.data[self.front]
self.data[self.front] = None
self.front = (self.front + 1) % len(self.data)
self.size -= 1
return value
q = CircularQueue(3)
q.enqueue("A")
q.enqueue("B")
print(q.dequeue()) # A
q.enqueue("C")
q.enqueue("D") # uses the wrapped position
print(q.dequeue()) # B| Operation | Index or condition | Time |
|---|---|---|
| Enqueue | `(front + size) % capacity` | O(1) |
| Dequeue | `front`, then increment modulo capacity | O(1) |
| Empty test | `size == 0` | O(1) |
| Full test | `size == capacity` | O(1) |
Common errors
A frequent mistake is using only front == rear to represent both empty and full. That representation needs an extra flag or a deliberately unused array slot. With a size field, the conditions are unambiguous.
Do not increment an index without modulo arithmetic. Otherwise, an operation after the last array position accesses an invalid index.
Exercise
A circular queue has capacity 6, front = 4, and size = 3. At which index will the next enqueue store its value?
Show answer
Index 1, because (4 + 3) % 6 = 1.