Sub topic 10
Circular Queues: Wrap-Around and Full/Empty Conditions
This chapter assumes you know the queue ADT (FIFO, enqueue, dequeue), array indexing, and the modulo operator. It covers why a plain array queue wastes space, how a circular queue fixes that, and how to tell a full queue from an empty one. GATE asks about these conditions often.
The problem with a linear array queue
A simple array queue keeps two indices. front marks the next element to remove, and rear marks where the next element goes. Enqueue moves rear right, and dequeue moves front right.
Indices only move forward. After a few dequeues, the cells before front are free, but rear has reached the end of the array. The queue reports "full" even though most of the array is empty.
| Step | Array (capacity 5) | front | rear | Result |
|---|---|---|---|---|
| Start | `_ _ _ _ _` | 0 | 0 | empty |
| Enqueue A, B, C, D, E | `A B C D E` | 0 | 5 | full |
| Dequeue twice | `_ _ C D E` | 2 | 5 | "full" but 2 cells are free |
The two free cells at the left cannot be used. Shifting every element left on each dequeue fixes this, but it costs O(n) per dequeue. A circular queue fixes it in O(1).
Wrap-around with modulo
A circular queue treats the array as a ring. When an index passes the last cell, it returns to cell 0. The formula for advancing an index in an array of capacity N is:
next(i) = (i + 1) mod NFor N = 5, the sequence of indices is 0, 1, 2, 3, 4, 0, 1, and so on. Nothing is shifted. Only the indices move.
Here front = 4 and the queue holds A, B, C in that order. C sits at cell 0 because the indices wrapped.
The full/empty ambiguity
Suppose you store only front and rear, where rear is the index of the next free cell. Then:
- The queue is empty when
front == rear. - If you fill every cell,
rearwraps around and also equalsfront.
Both states give front == rear. The two indices alone cannot tell them apart. There are three standard fixes.
Fix 1: Sacrifice one cell
Never let the queue hold more than N - 1 elements. Then front == rear always means empty, and a full queue is detected as:
(rear + 1) mod N == frontThis is the default convention in many GATE questions and textbooks. The cost is one unused cell, so the usable capacity is N - 1.
Fix 2: Keep a count
Store a size variable. The queue is empty when size == 0 and full when size == N. All N cells are usable. This is the approach in the code below.
Fix 3: Use a flag
Store a boolean that records whether the last operation was an enqueue or a dequeue. If front == rear and the last operation was an enqueue, the queue is full. If it was a dequeue, the queue is empty. This also uses all N cells but adds bookkeeping to every operation.
| Method | Empty test | Full test | Usable capacity |
|---|---|---|---|
| Sacrifice a cell | `front == rear` | `(rear + 1) % N == front` | N - 1 |
| Count | `size == 0` | `size == N` | N |
| Flag | `front == rear` and last op was dequeue | `front == rear` and last op was enqueue | N |
Implementation with a count
This version keeps front and size. The rear position is derived, so only two fields change per operation.
class CircularQueue:
def __init__(self, capacity):
self.a = [None] * capacity
self.front = 0
self.size = 0
def enqueue(self, x):
if self.size == len(self.a):
raise OverflowError('queue full')
self.a[(self.front + self.size) % len(self.a)] = x
self.size += 1
def dequeue(self):
if self.size == 0:
raise IndexError('queue empty')
x = self.a[self.front]
self.front = (self.front + 1) % len(self.a)
self.size -= 1
return xEnqueue writes at (front + size) % N, which is the first free cell. Dequeue reads at front, then advances front with wrap-around. Both run in O(1) time and the structure uses O(N) space.
Computing positions and element counts
GATE questions often give front and rear and ask for the number of elements. Take rear as the next free index, with the sacrifice-a-cell convention.
count = (rear - front + N) mod NFor N = 8, front = 6, rear = 2, the count is (2 - 6 + 8) mod 8 = 4. The elements sit in cells 6, 7, 0, 1.
The + N matters. In languages such as C and Java, % on a negative number gives a negative result. In Python, % always returns a non-negative result for a positive modulus, but you should still write the formula so it works everywhere.
The convention for rear changes the answer, so always check which one the question uses:
| Convention | `rear` means | Empty | Full (sacrifice a cell) | Count |
|---|---|---|---|---|
| Next free cell | Index where the next element goes | `front == rear` | `(rear + 1) % N == front` | `(rear - front + N) % N` |
| Last element | Index of the most recent element | Special marker, such as `front == -1` | `(rear + 1) % N == front` | `(rear - front + N) % N + 1` |
With the "last element" convention, front == (rear + 1) % N does not by itself separate a full queue from an empty one, so implementations add a marker like front = -1 for empty.
Worked trace
Take N = 4, using the count-based code above.
- Enqueue 10, 20, 30. Cells:
10 20 30 _,front = 0,size = 3. - Dequeue returns 10.
front = 1,size = 2. - Enqueue 40. It goes to
(1 + 2) % 4 = 3. Cells:_ 20 30 40,size = 3. - Enqueue 50. It goes to
(1 + 3) % 4 = 0. Cells:50 20 30 40,size = 4. The queue is full. - Enqueue 60 raises
OverflowError.
Step 4 is the wrap-around: the element is stored in cell 0, which a linear queue could never reuse.
Edge cases and common errors
- Using
front == rearas the only test, with no extra state, makes full and empty indistinguishable once the queue can fill every cell. - Forgetting to wrap
rearon enqueue, orfronton dequeue, causes an out-of-bounds access. - Writing
rear - frontwithout+ Ngives a negative count whenrear < front. - Mixing conventions, for example computing the full test for the "sacrifice a cell" scheme but sizing the array for the count scheme, causes off-by-one errors.
- In a multi-threaded program, a count shared by producer and consumer needs synchronization. Sacrificing a cell lets each side change only one index, which is why ring buffers in systems code often use it.
- Dequeuing from an empty queue is underflow. Enqueuing into a full queue is overflow. Both must be checked before touching the array.
Cost summary
| Operation | Time | Notes |
|---|---|---|
| Enqueue | O(1) | One write and one modulo |
| Dequeue | O(1) | One read and one modulo |
| Peek | O(1) | Reads `a[front]` |
| Full/empty test | O(1) | Compare indices or the count |
| Space | O(N) | Fixed capacity chosen at creation |
The main limit is the fixed capacity. A full circular queue must either reject new elements or be copied into a larger array, and the copy must unwrap elements so that front becomes 0 in the new array.
Exercise
A circular queue uses an array of size 10 and the "sacrifice one cell" convention, where rear is the index of the next free cell and the queue is empty when front == rear. Currently front = 7 and rear = 3. (a) How many elements does the queue hold? (b) How many more can be enqueued before it is full?
Show answer
(a) The count is (3 - 7 + 10) mod 10 = 6, held in cells 7, 8, 9, 0, 1, 2. (b) The maximum is N - 1 = 9 elements, so 9 - 6 = 3 more can be enqueued. Check: after three enqueues, rear = 6 and (6 + 1) mod 10 = 7 = front, which is the full condition.
Exercise
A circular queue has capacity 5 and uses the count-based implementation. Starting empty, the operations enqueue(1), enqueue(2), enqueue(3), dequeue, dequeue, enqueue(4), enqueue(5), enqueue(6), enqueue(7) are applied. What happens, and what are the final array contents and front?
Show answer
After the first five operations, front = 2 and size = 1 (element 3 in cell 2). enqueue(4) goes to cell 3, enqueue(5) to cell 4, enqueue(6) to cell (2 + 3) % 5 = 0, so size = 4. enqueue(7) goes to cell (2 + 4) % 5 = 1, so size = 5 and the queue is full. No error occurs. The array is [6, 7, 3, 4, 5] and front = 2. Reading from front gives 3, 4, 5, 6, 7. The stale values 1 and 2 were overwritten, so the final array does not contain them.