#1 India's Top IT Training Institute
×

About Uncodemy

Know more about who we are and what we stand for.

About Us

About Us

Discover our mission to equip individuals with essential IT skills and industry expertise.

Read More →
UnCodeMy Gallery

UnCodeMy Gallery

Explore highlights from our IT training sessions and success stories.

Read More →
Mentors

Mentors

Meet the industry experts who train and guide you through your course.

Read More →
Free Resources

Free Resources

Free tutorials, interview questions, tools and calculators to help you learn.

Explore →
×

Free Resources

Learn, practice and plan your career — bilkul free.

Tutorials

Tutorials

Step-by-step written tutorials to learn any technology at your own pace.

Read More →
Free Counselling

Free Counselling

Book a free video counselling session and pick the right course for you.

Read More →
Online Compiler

Online Compiler

Write, run and test your code online — no setup required.

Read More →
Queues

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

OperationTime
EnqueueO(1)
DequeueO(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.

OperationfrontrearsizeArray contents
enqueue(10)001[10, -, -, -]
enqueue(20)012[10, 20, -, -]
enqueue(30)023[10, 20, 30, -]
dequeue() returns 10122[x, 20, 30, -]
dequeue() returns 20221[x, x, 30, -]
enqueue(40)232[x, x, 30, 40]
enqueue(50)203[50, x, 30, 40]
enqueue(60)214[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 + 1 without % capacity, which causes an index error at the end of the array.
  • Relying on front == rear alone to detect both empty and full states.
  • Starting rear at 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.