Circular Queue Simulation
Simulate a circular queue with a fixed capacity using an array. A circular queue is a FIFO data structure that reuses space at the beginning of the array when the end is reached, using modulo arithmetic to wrap indices around. Implement the core operations: enqueue (add to rear), dequeue (remove from front), peek front, peek rear, check empty, and check full.
For example, a circular queue with capacity 3: enqueue 1, 2, 3 fills it. Dequeue removes 1 (front). Enqueue 4 succeeds by wrapping to index 0. Enqueue 5 fails because the queue is full. The queue holds [4, 2, 3] with front at index 1 and rear at index 0.
Circular queues are used in buffering systems (audio/video streaming buffers), CPU scheduling (round-robin process queues), and data transfer (ring buffers). The circular reuse of space makes them memory-efficient compared to linear queues that shift elements on dequeue.
The implementation tracks a front index, a rear index, and a size counter. Enqueue places the element at (front + size) % capacity and increments size. Dequeue advances front to (front + 1) % capacity and decrements size. Both operations run in O(1) time without shifting elements.
Edge cases include an empty queue (front and rear return -1), a full queue (enqueue returns false), and the wrap-around case where front has advanced past the array's physical end but logical indices wrap via modulo.
Example Input & Output
Empty
Size 5
Circular queue of size 3 with values 0..2
Size 2
Size 1
Algorithm Flow
Solution Approach
Use an array with front and size tracking to implement the circular queue. The rear position is derived as (front + size) % capacity, avoiding a separate rear variable that must be carefully maintained.
The modulo operation wraps indices within the array bounds. The size counter distinguishes empty from full states. All operations are O(1).
Time O(1), Space O(k).
Best Answers
class Solution {
public int[] solution(int n) {
int[] r=new int[n];
for(int i=0;i<n;i++)r[i]=i;
return r;
}
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
