Elements in a circular queue — Aptitude Question
Elements in a circular queue: A circular queue occupies an array of 8 slots, with one slot always left empty so… Answer and worked solution on CodeKairo.
- Topic: Data Structures & Algorithms
- Section: Programming MCQs
- Difficulty: Medium
- Time target: 90 seconds
Question
A circular queue occupies an array of 8 slots, with one slot always left empty so that full and empty can be told apart. front indexes the first element and rear indexes the next free slot. If front = 4 and rear = 3, how many elements does the queue hold?
Options
- 0
- 1
- 7
- 8
Show the answer and the worked solution
Correct answer: C. 7
Worked solution
- With
rearpointing at the next free slot, the number of elements is (rear − front + n) mod n. - Substituting the values gives (3 − 4 + 8) mod 8 = 7 mod 8 = 7.
- Since one slot is deliberately left empty, 7 is the largest an eight-slot array can hold, so the queue is in fact full.
Answer: 7.
The idea
Adding n before taking the modulus keeps the arithmetic correct when rear has wrapped past front. Leaving one slot unused is the standard trick that makes (rear + 1) mod n == front mean 'full'.
Shortcut. rear sits one slot behind front, (3 + 1) mod 8 = 4, which is the definition of full in the one-empty-slot scheme: capacity 8 − 1 = 7.
Common trap. 1 takes the gap front − rear = 4 − 3 without adding n, measuring the empty stretch instead of the occupied one.
All Data Structures & Algorithms questions · placement mock tests