Medium

Quiz

#622 Design Circular Queue

APPROACH

Implement a circular queue (also known as a Ring Buffer) with fixed capacity k using FIFO ordering where the tail wraps back around to the head. Design the MyCircularQueue class with: MyCircularQueue(k) to initialize with capacity k; enQueue(value) to insert and return true on success; deQueue() to remove from front and return true on success; Front() and Rear() to peek at the front/back (return -1 if empty); isEmpty() and isFull() status checks. Do not use a built-in queue.

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]

Example 2:

Explanation
MyCircularQueue myCircularQueue = new MyCircularQueue(3);
myCircularQueue.enQueue(1); // return True
myCircularQueue.enQueue(2); // return True
myCircularQueue.enQueue(3); // return True
myCircularQueue.enQueue(4); // return False
myCircularQueue.Rear(); // return 3
myCircularQueue.isFull(); // return True
myCircularQueue.deQueue(); // return True
myCircularQueue.enQueue(4); // return True
myCircularQueue.Rear(); // return 4
1 of 4
1:00

What is the optimal approach for this problem?