Skip to content
Onsite

Design Circular Queue

MediumP2Coding

Design a circular queue of fixed capacity k backed by a single array of size k. The last position connects back to the first, so freed slots at the front are reused.

Implement the MyCircularQueue class:

  • MyCircularQueue(k) sets the capacity.
  • enQueue(value) adds at the rear; returns true on success, false if the queue is full.
  • deQueue() removes from the front; returns true on success, false if the queue is empty.
  • Front() returns the front value, or -1 if empty.
  • Rear() returns the rear value (the most recently added still in the queue), or -1 if empty.
  • isEmpty() and isFull() report the state.

Every operation is O(1). Do not use a resizable list as the queue itself.

Example 1

Input
["MyCircularQueue","enQueue","enQueue","enQueue","enQueue","Rear","isFull","deQueue","enQueue","Rear"] [[3],[1],[2],[3],[4],[],[],[],[4],[]]
Output
[null,true,true,true,false,3,true,true,true,4]
Why
After the dequeue a slot is free, so the next enQueue wraps around and succeeds.

Constraints

  • 1 <= k <= 1000
  • 0 <= value <= 1000
  • At most 3000 calls.

Hints

Run checks the 2 visible tests, Submit all 7.