In an array-based implementation of a circular queue, overflow occurs when
2026
In an array-based implementation of a circular queue, overflow occurs when
- A.
rear == front
- B.
rear == size - 1
- C.
front == -1
- D.
(rear + 1) % size == front
Show answer & explanation
Correct answer: D
Concept
A circular queue stores elements in a fixed-size array and treats that array as wrapping around: after every enqueue, rear advances by one position modulo the array size, i.e. rear = (rear + 1) % size; after every dequeue, front advances the same way. This scheme reserves one array slot so that front equal to rear can unambiguously mean the queue is empty; consequently, a size-N array holds at most N-1 elements at once. The queue has become full -- the next enqueue would overflow -- exactly when the position rear would move to next equals front's current index, i.e. (rear + 1) % size == front.
Applying it here
Take size = 4 (valid indices 0, 1, 2, 3) and start with an empty queue: front = 0, rear = 0. Because one slot must always stay reserved under this convention, this array can hold at most 3 elements at a time.
Enqueue three elements in turn (call them A, B, C): each enqueue stores the element at index rear, then sets rear = (rear + 1) % size. After all three enqueues, front is still 0 and rear has advanced from 0 to 1 to 2 to 3 -- so front = 0, rear = 3, with A, B, C stored at indices 0, 1, 2.
Dequeue one element (A): front advances the same way, front = (0 + 1) % 4 = 1. The queue now holds B and C at indices 1 and 2, with front = 1, rear = 3.
Enqueue one more element (D): store it at index rear = 3, then update rear = (3 + 1) % 4 = 0. The queue now holds B, C, D at indices 1, 2, 3 -- three elements, with front = 1, rear = 0.
Before allowing a further enqueue, evaluate the overflow test: compute (rear + 1) % size = (0 + 1) % 4 = 1, which equals front (1). The test is true, so this further enqueue is blocked -- this is overflow, even though physical index 0 is still empty; that index is the slot this convention permanently reserves so that front equal to rear can mean exactly 'empty'.
Cross-check
The classic reason a circular queue needs this modulo-based full test, rather than reusing rear equal to front, is that rear equal to front already serves as the EMPTY test (for example, the initial state before anything is enqueued). If fullness were also tested the same way, empty and full states could not be told apart by that one equality. In the worked trace above, the full state has front at index 1 and rear at index 0 -- rear is not equal to front there, so that plain equality could never have signalled this particular overflow; only the modulo-based next-position test correctly ties fullness to a state distinct from empty.