Design Circular Queue

Implement a fixed-size first-in-first-out queue on top of an array whose end wraps around to its start, so slots freed at the front can be reused at the back. Support enQueue, deQueue, Front, Rear, isEmpty and isFull without using a built-in queue.

30:00

Design Circular Queue
medium
Free written solution
Topics
Companies

Implement a fixed-size first-in-first-out queue on top of an array whose end wraps around to its start, so slots freed at the front can be reused at the back. Support enQueue, deQueue, Front, Rear, isEmpty and isFull without using a built-in queue.

Example 1:
Input: {"commands":["MyCircularQueue","enQueue","enQueue","enQueue","enQueue","Rear","isFull","deQueue","enQueue","Rear"],"values":[[3],[1],[2],[3],[4],[],[],[],[4],[]]}
Output: [null,true,true,true,false,3,true,true,true,4]
Constraints:
  • 1≤k≤10001 \leq k \leq 1000

  • 0≤value≤10000 \leq \text{value} \leq 1000

  • At most 30003000 calls will be made to enQueue, deQueue, Front, Rear, isEmpty, and isFull.

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"commands":["MyCircularQueue","enQueue","enQueue","enQueue","enQueue","Rear","isFull","deQueue","enQueue","Rear"],"values":[[3],[1],[2],[3],[4],[],[],[],[4],[]]}
new(3)
enQueue(1)
enQueue(2)
enQueue(3)
enQueue(4)
Rear()
isFull()
deQueue()
enQueue(4)

…

10 calls to run on a ring of 3 slots. head marks the front; the next write goes to (head + count) % k.

012headtailcount0/3
● live value● stale or unused slothead fronttail next write

Queue as the caller sees it (front to rear)

(empty)

Returned values

[]
Variables
VariableValue
call
head0
count0
tail0
output[]
DepthFunction Call
Stack empty
0/10