Introduction
A Circular Queue is an advanced version of a normal queue where:
Last position connects back to first positionThis removes wasted spaces created in normal array queues.
Circular Queue follows:
FIFOFirst In First OutThis problem helps in understanding:
- modular arithmetic
- array queues
- circular traversal
- efficient memory usage
Example
Queue Size = 5Operations:
enqueue(10)
enqueue(20)
enqueue(30)
dequeue()
enqueue(40)
Queue becomes:
[20, 30, 40]
Constraints
1 <= queueSize <= 10^5Approach : Circular Array
Explanation
Circular Queue uses:
- front pointer
- rear pointer
Important idea:
(next index) % sizeWhen rear reaches end:
- it wraps back to start
This allows:
- efficient reuse of empty spaces
Steps
- Initialize queue array.
- Maintain front and rear.
- Insert using circular indexing.
- Remove using circular indexing.
- Detect full and empty conditions.
Dry Run
Queue Size:5
Initial:
front = -1
rear = -1
enqueue(10)
front = 0
rear = 0
Queue:
[10]
enqueue(20)
rear = (0 + 1) % 5
rear = 1
Queue:
[10, 20]
dequeue()
Remove:
10
front = 1
Queue:
[20]
enqueue(30) rear = 2
Final Queue:
[20, 30]
Circular Queue Code
Complexity Analysis
Enqueue Time Complexity: O(1)Dequeue Time Complexity: O(1)
Explanation:
Direct index access is used.
Space Complexity: O(n) Explanation:
Array is used to store queue elements.
Edge Cases
- Queue full
- Queue empty
- Single element queue
- Wrap-around condition
- Continuous enqueue and dequeue
Why This Problem is Important
Circular Queue helps in understanding:
- Queue implementation
- Modular arithmetic
- Circular traversal
- Efficient memory usage
- FIFO processing
It is one of the most important queue interview problems.
Real-World Applications
Circular Queue concepts are used in:
- CPU scheduling
- Buffers
- Streaming systems
- Network packet handling
- Keyboard input systems
Common Mistakes
- Incorrect full condition
- Wrong modulo calculation
- Forgetting wrap-around logic
- Incorrect empty queue handling
Interview Tips
Interviewers often expect:
- Circular indexing explanation
- Queue full condition understanding
- Modulo arithmetic usage
Always explain:
- why modulo is needed
- how wrap-around works
- why memory wastage is avoided
Related Questions
- Design Queue
- Implement Queue using Stack
- Deque Implementation
- Sliding Window Maximum
- LRU Cache
Final Takeaway
Circular Queue is a fundamental queue implementation problem that teaches modular indexing and efficient memory reuse techniques. Understanding Circular Queue builds a strong foundation for advanced queue and buffering interview problems.