A circular queue uses an array where the end connects back to the start, so we reuse empty spaces efficiently.
Analogy: Imagine a round table with seats numbered in a circle. When you reach the last seat, you go back to the first seat to sit if it's free.
Front -> [ ] [ ] [ ] [ ] [ ] ← Rear
Index -> 0 1 2 3 4
Initially all empty, front and rear at -1
Dry Run Walkthrough
Input: Create circular queue of size 5, enqueue 3 elements (10, 20, 30), dequeue 1 element, enqueue 2 elements (40, 50), then enqueue 1 element (60) to test wrap-around
Goal: Show how elements wrap around in the array and how front and rear pointers move
Time: O(1) for enqueue and dequeue because we only move pointers and assign values without shifting elements
Space: O(n) because we use a fixed-size array of size n to store elements
vs Alternative: Compared to a normal queue using array that shifts elements on dequeue (O(n)), circular queue avoids shifting by wrapping pointers, making operations O(1)
Edge Cases
Empty queue dequeue
Prints 'Queue is empty' and returns -1 without crashing
DSA C
if (isEmpty(q)) { printf("Queue is empty\n"); return -1; }
Full queue enqueue
Prints 'Queue is full' and does not add element
DSA C
if (isFull(q)) { printf("Queue is full\n"); return; }
Single element enqueue and dequeue
Front and rear reset to -1 after removing last element
When you need a queue with fixed size and want to reuse freed spaces efficiently, use circular queue with array to avoid costly shifts.
Common Mistakes
Mistake: Not wrapping rear or front pointers using modulo, causing index out of bounds Fix: Always update pointers with modulo operation: (pointer + 1) % SIZE
Mistake: Not resetting front and rear to -1 when queue becomes empty after dequeue Fix: Check if front equals rear after dequeue and reset both to -1
Summary
Implements a queue using a fixed-size array where rear wraps to front to reuse space.
Use when you want efficient fixed-size queue operations without shifting elements.
The key is to move front and rear pointers circularly using modulo to manage wrap-around.