Data Structures · Visualization
Circular Queue: Introduction
Circular Queue
A circular queue is a fixed-size array-based queue where the front and rear pointers wrap around to index 0 after reaching the end, reusing freed slots instead of shifting elements — solving the wasted-space problem of a simple array queue. Time: Enqueue/Dequeue: O(1). Space: O(capacity).
Big-O: enqueue / dequeue both O(1) via wrap-around indices on a fixed array.
Circular Queue: Introduction
Circular QueueA circular queue is a fixed-size array-based queue where the front and rear pointers wrap around to index 0 after reaching the end, reusing freed slots instead of shifting elements — solving the wasted-space problem of a simple array queue.
How Circular Queue: Introduction Works
- Allocate a fixed-size array plus front and rear indices, both starting at -1 (empty).
- Track size (or use a full/empty flag) since front === rear is ambiguous between empty and full.
- On enqueue, advance rear using rear = (rear + 1) % capacity.
- On dequeue, advance front using front = (front + 1) % capacity.
- The queue is full when size === capacity, and empty when size === 0.
Circular Queue: Introduction Worked Example
Input: Capacity 4, enqueue 10, 20, 30, dequeue once, enqueue 40, 50
- enqueue 10 → [10,_,_,_] front=0 rear=0
- enqueue 20,30 → [10,20,30,_] rear=2
- dequeue → removes 10, front=1
- enqueue 40 → [10,20,30,40] rear=3
- enqueue 50 → wraps: rear=(3+1)%4=0 → [50,20,30,40] front=1
Output: Queue holds 20,30,40,50 in order, reusing slot 0
Press ▶ Run to watch it step by step.
class CircularQueue:
def __init__(self, cap):
self.q = [None] * cap
self.head = self.tail = 0
self.size = 0
self.cap = cap
def enqueue(self, v): # head/tail wrap with %
if self.size == self.cap:
raise RuntimeError("full")
self.q[self.tail] = v
self.tail = (self.tail + 1) % self.cap
self.size += 1
def dequeue(self):
if self.size == 0:
raise RuntimeError("empty")
v = self.q[self.head]
self.head = (self.head + 1) % self.cap
self.size -= 1
return v
q = CircularQueue(4)
q.enqueue(3) # no shifting needed:
q.dequeue() # wrap-around in O(1)
# example: viewCircular Queue: Introduction Time & Space Complexity
When to Use Circular Queue: Introduction
- CPU / IO buffering
- Streaming media buffers
- Traffic light / round-robin resource sharing
Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Ready for the next step?
See the same ideas in action — visualize the algorithms that operate on these structures, or take a guided course.