AAlgoLoopSpaced repetition for LeetCode
MEDIUMDesignLeetCode ↗

Design Circular Queue

The key idea

Store the items in a fixed array of size k and track a head index plus a count of live items. Every position is taken modulo k, so the tail wraps around to reuse the slots that deQueue freed — no element shifting and every operation is O(1).

Problem

Design your implementation of a circular queue. A circular queue is a linear data structure that follows FIFO (First In First Out) order, but the last position is connected back to the first position to form a ring. It is also called a ring buffer.

The benefit of a circular queue is that we can use the spaces in front of the queue. In a normal queue, once it becomes full we cannot insert the next element even though there is empty space at the front. With a circular queue, those freed spaces can be reused.

Implement the MyCircularQueue class:

- MyCircularQueue(k) initializes the queue with a fixed capacity of k.
- enQueue(value) inserts value at the rear of the queue. Return true if the operation is successful, or false if the queue is full.
- deQueue() removes an element from the front of the queue. Return true if successful, or false if the queue is empty.
- Front() returns the front item, or -1 if the queue is empty.
- Rear() returns the rear item, or -1 if the queue is empty.
- isEmpty() returns true if the queue is empty.
- isFull() returns true if the queue is full.

You must implement each operation in O(1) time and you are not allowed to use the built-in queue library.

Constraints

Examples

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]
Input: ["MyCircularQueue","enQueue","Front","deQueue","isEmpty"] [[2],[5],[],[],[]] Output: [null,true,5,true,true]

Complexity

Time: O(1) Space: O(k)

See the full solution

410310
Step-by-step visualization
Start free →

More Design problems