Circular Queue Implementation Using Array in DSA C - Time & Space Complexity
We want to understand how the time needed to add or remove items changes as the queue grows.
How does the circular queue handle operations as more elements are added or removed?
Analyze the time complexity of the following circular queue operations.
#define SIZE 5
int queue[SIZE];
int front = -1, rear = -1;
void enqueue(int value) {
if ((rear + 1) % SIZE == front) return; // Queue full
if (front == -1) front = 0;
rear = (rear + 1) % SIZE;
queue[rear] = value;
}
int dequeue() {
if (front == -1) return -1; // Queue empty
int val = queue[front];
if (front == rear) front = rear = -1;
else front = (front + 1) % SIZE;
return val;
}
This code adds (enqueue) and removes (dequeue) elements in a circular queue using an array.
Look for loops or repeated steps inside the operations.
- Primary operation: Single step index update and assignment in enqueue and dequeue.
- How many times: Each enqueue or dequeue runs once per call, no loops inside.
Each enqueue or dequeue does a fixed number of steps regardless of queue size.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 5-6 steps per operation |
| 100 | 5-6 steps per operation |
| 1000 | 5-6 steps per operation |
Pattern observation: The number of steps stays the same no matter how many items are in the queue.
Time Complexity: O(1)
This means each enqueue or dequeue operation takes the same short time no matter how big the queue is.
[X] Wrong: "Enqueue or dequeue takes longer as the queue gets bigger because the array is large."
[OK] Correct: The circular queue uses index math to jump directly to the right spot, so it never scans the whole array.
Understanding constant time operations in circular queues shows you can manage fixed-size buffers efficiently, a useful skill in many real-world systems.
"What if we changed the circular queue to a normal queue without wrapping? How would the time complexity of enqueue and dequeue change?"
