Bird
0
0
DSA Cprogramming~5 mins

Circular Queue Implementation Using Array in DSA C - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Circular Queue Implementation Using Array
O(1)
Understanding Time 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?

Scenario Under Consideration

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.

Identify Repeating Operations

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.
How Execution Grows With Input

Each enqueue or dequeue does a fixed number of steps regardless of queue size.

Input Size (n)Approx. Operations
105-6 steps per operation
1005-6 steps per operation
10005-6 steps per operation

Pattern observation: The number of steps stays the same no matter how many items are in the queue.

Final Time Complexity

Time Complexity: O(1)

This means each enqueue or dequeue operation takes the same short time no matter how big the queue is.

Common Mistake

[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.

Interview Connect

Understanding constant time operations in circular queues shows you can manage fixed-size buffers efficiently, a useful skill in many real-world systems.

Self-Check

"What if we changed the circular queue to a normal queue without wrapping? How would the time complexity of enqueue and dequeue change?"