Home
DSA Course
Data Structures
Circular Queue
Circular Queue
A fixed-size queue that reuses empty slots at the beginning when the end is reached.
See the Logic in Motion
Stop memorizing code. Unlock the full interactive visualizer to master the logic step-by-step.Intuition
A standard array-based queue has a major flaw: as you dequeue items, the 'front' moves forward, leaving unused empty space at the beginning. A Circular Queue connects the end back to the beginning, forming a circle. This ensures no space is wasted.
Think of it as a Ring Buffer used in traffic light controllers or CPU scheduling.
Concept
It utilizes modular arithmetic logic: next_index = (current_index + 1) % capacity.
- Front: Index of the first element.
- Rear: Index of the last element.
- Full Condition:
(rear + 1) % capacity == front - Empty Condition:
front == -1
How it Works
When you seek to enqueue an element:
- Check if full. If not, calculate new rear:
(rear + 1) % size. - Insert data.
When you dequeue:
- Check if empty. If not, retrieve data at front.
- Move front:
(front + 1) % size. - If front passes rear (queue becomes empty), reset both to -1.
Step-by-Step Breakdown
- Enqueue 10: Rear moves from -1 to 0. Arr[0] = 10.
- Enqueue 20: Rear moves to 1. Arr[1] = 20.
- Dequeue: Front moves to 1. Space at 0 is potentially reusable.
- Wrap Around: If Rear is at index N-1 and index 0 is free, Rear wraps to 0.
When to Use
- Memory Management: Buffering data streams (e.g., video buffering).
- Traffic Systems: Cyclic round-robin scheduling.
- Fixed Resource Pools: When total capacity is strictly limited.
When NOT to Use
- When you need dynamically growing storage (use a Linked List or dynamic Deque).
- When random access to the middle of the queue is required.
How to Identify
Problems asking for 'design a buffer', 'round robin', or 'moving average' over a fixed window size usually imply a Circular Queue/Buffer.
Stop Guessing, Start Mastering.
Build the FAANG intuition. Master this pattern with optimized implementations, visual dry runs, and our curated collection of high-yield problems.
