15% off all plans & roadmaps Use code
See plansDesign Circular Queue
- LeetCode 622
- Medium
- Design Patterns
- Design (General/Specific)
Updated
TL;DR: Build a fixed-size ring buffer that keeps a head index and an item count, so every operation runs in O(1) time. A plain list shifts every item on each dequeue, which does work the queue never needs.
Problem
Design a circular queue. A circular queue is a linear data structure that follows first in, first out (FIFO) order. Its last position connects back to its first position, which forms a circle. People also call it a Ring Buffer.
The main benefit is reuse. In a normal queue, once the back reaches the end of the storage, you cannot insert a value even when the slots at the front are empty. A circular queue wraps around and uses those slots.
Implement the MyCircularQueue class:
MyCircularQueue(k)initializes the queue with sizek.int Front()returns the front item. If the queue is empty, return-1.int Rear()returns the last item. If the queue is empty, return-1.boolean enQueue(int value)inserts an element. Returntrueif the operation succeeds.boolean deQueue()removes an element. Returntrueif the operation succeeds.boolean isEmpty()checks whether the queue is empty.boolean isFull()checks whether the queue is full.
You must solve the problem without the built-in queue data structure of your language.
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] 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
Constraints
1 <= k <= 10000 <= value <= 1000- At most
3000calls will be made toenQueue,deQueue,Front,Rear,isEmpty, andisFull.
Constraints that matter
- k is at least 1, so the modulo by k never divides by zero and the array always has a slot to write.
- Values are never negative, so -1 is free to signal an empty queue from Front and Rear.
- Up to 3000 calls means each call must do a small, fixed amount of work. A cost of O(k) per call would still pass, but the interview expects the O(1) bound.
- Capacity is at most 1000, so the array can be allocated once in the constructor and never resized.
Hints
Hint 1
A circular queue needs two facts at every moment: where the front item sits, and how many items are stored.
Hint 2
A beginner usually stores the items in a plain list.
Solution
Intuition
A circular queue needs two facts at every moment: where the front item sits, and how many items are stored. The values live in a fixed array of k slots. Once you know the head index and the count, you can find every item and every free slot without moving anything.
This is a design problem built on index arithmetic, usually called a ring buffer. The array has k slots, but the queue must keep accepting values after the end of the array. Taking an index modulo k sends it back to the start, so the array behaves like a circle.
Why track a count instead of comparing head and tail? When head equals tail, the queue could be empty or full, and both states look the same. A count separates the two cases. The tail index never needs storage, because it is always (head + count) mod k.
Take k = 3. enQueue(1), enQueue(2), and enQueue(3) fill slots 0, 1, and 2, and head stays at 0. deQueue moves head to 1 and drops count to 2. enQueue(4) writes to slot (1 + 2) mod 3, which is slot 0, the slot freed at the front. Count is now 3, so Rear reads slot (1 + 3 - 1) mod 3, which is slot 0 and holds 4.
Worked example
Input: commands = ["MyCircularQueue", "Front", "Rear", "isEmpty", "isFull", "deQueue"] arguments = [[2], [], [], [], [], []] Output: [null, -1, -1, true, false, false] Explanation: The queue has capacity 2 and starts empty. Front and Rear return -1 because nothing is stored. isEmpty returns true. isFull returns false because the count is 0, not 2. deQueue returns false because there is nothing to remove.
Approach 1: Brute force with a plain list
A beginner usually stores the items in a plain list. enQueue appends to the end, and deQueue removes the first element. The list keeps the items in order, so every answer is correct. The cost sits in deQueue, which removes index 0. Every remaining item shifts one slot left, so each dequeue does work that grows with the number of items stored.
Steps
- Create an empty list and store the capacity k.
- In enQueue, return false if the list already holds k items. Otherwise append the value and return true.
- In deQueue, return false if the list is empty. Otherwise remove index 0 and return true.
- Front returns the first item, and Rear returns the last item. Both return -1 when the list is empty.
- isEmpty checks that the length is 0. isFull checks that the length equals k.
Dry run
Start with k = 2 and the list []. Front returns -1 because the list is empty. Rear returns -1 for the same reason. isEmpty returns true. isFull compares the length 0 with 2 and returns false. deQueue sees an empty list and returns false. The outputs are [null, -1, -1, true, false, false], which matches the example.
Complexity
| Time | O(k) per deQueue, O(1) for the other operations |
|---|---|
| Space | O(k) |
Let n be the number of items stored, where n is at most k. Removing index 0 moves the other n - 1 items one slot left, so deQueue does O(n) work, which is O(k) in the worst case. enQueue, Front, Rear, isEmpty, and isFull touch one slot or read a length, so each does constant work. The list never holds more than k items, so the space is O(k).
PythonTested in our runner
from typing import List, Optional
class MyCircularQueue:
def __init__(self, k: int):
self.capacity = k
self.items = []
def enQueue(self, value: int) -> bool:
if self.isFull():
return False
self.items.append(value)
return True
def deQueue(self) -> bool:
if self.isEmpty():
return False
self.items.pop(0) # shifts every remaining item left
return True
def Front(self) -> int:
if self.isEmpty():
return -1
return self.items[0]
def Rear(self) -> int:
if self.isEmpty():
return -1
return self.items[-1]
def isEmpty(self) -> bool:
return len(self.items) == 0
def isFull(self) -> bool:
return len(self.items) == self.capacityJavaTested in our runner
import java.util.*;
class MyCircularQueue {
private ArrayList<Integer> items = new ArrayList<>();
private int capacity;
public MyCircularQueue(int k) {
capacity = k;
}
public boolean enQueue(int value) {
if (isFull()) return false;
items.add(value);
return true;
}
public boolean deQueue() {
if (isEmpty()) return false;
items.remove(0); // shifts every remaining item left
return true;
}
public int Front() {
if (isEmpty()) return -1;
return items.get(0);
}
public int Rear() {
if (isEmpty()) return -1;
return items.get(items.size() - 1);
}
public boolean isEmpty() {
return items.isEmpty();
}
public boolean isFull() {
return items.size() == capacity;
}
}C++Tested in our runner
class MyCircularQueue {
private:
std::vector<int> items;
int capacity;
public:
MyCircularQueue(int k) {
capacity = k;
}
bool enQueue(int value) {
if (isFull()) return false;
items.push_back(value);
return true;
}
bool deQueue() {
if (isEmpty()) return false;
items.erase(items.begin()); // shifts every item left
return true;
}
int Front() {
if (isEmpty()) return -1;
return items.front();
}
int Rear() {
if (isEmpty()) return -1;
return items.back();
}
bool isEmpty() {
return items.empty();
}
bool isFull() {
return (int)items.size() == capacity;
}
};JavaScriptTested in our runner
var MyCircularQueue = function(k) {
this.capacity = k;
this.items = [];
};
/**
* @param {number} value
* @return {boolean}
*/
MyCircularQueue.prototype.enQueue = function(value) {
if (this.isFull()) return false;
this.items.push(value);
return true;
};
/**
* @return {boolean}
*/
MyCircularQueue.prototype.deQueue = function() {
if (this.isEmpty()) return false;
this.items.shift(); // shifts every remaining item left
return true;
};
/**
* @return {number}
*/
MyCircularQueue.prototype.Front = function() {
if (this.isEmpty()) return -1;
return this.items[0];
};
/**
* @return {number}
*/
MyCircularQueue.prototype.Rear = function() {
if (this.isEmpty()) return -1;
return this.items[this.items.length - 1];
};
/**
* @return {boolean}
*/
MyCircularQueue.prototype.isEmpty = function() {
return this.items.length === 0;
};
/**
* @return {boolean}
*/
MyCircularQueue.prototype.isFull = function() {
return this.items.length === this.capacity;
};GoTested in our runner
type MyCircularQueue struct {
items []int
capacity int
}
func Constructor(k int) MyCircularQueue {
return MyCircularQueue{items: make([]int, 0, k), capacity: k}
}
func (this *MyCircularQueue) enQueue(value int) bool {
if this.isFull() {
return false
}
this.items = append(this.items, value)
return true
}
func (this *MyCircularQueue) deQueue() bool {
if this.isEmpty() {
return false
}
// shift every remaining item one slot left
copy(this.items, this.items[1:])
this.items = this.items[:len(this.items)-1]
return true
}
func (this *MyCircularQueue) Front() int {
if this.isEmpty() {
return -1
}
return this.items[0]
}
func (this *MyCircularQueue) Rear() int {
if this.isEmpty() {
return -1
}
return this.items[len(this.items)-1]
}
func (this *MyCircularQueue) isEmpty() bool {
return len(this.items) == 0
}
func (this *MyCircularQueue) isFull() bool {
return len(this.items) == this.capacity
}C#Tested in our runner
public class MyCircularQueue {
private List<int> items = new List<int>();
private int capacity;
public MyCircularQueue(int k) {
capacity = k;
}
public bool enQueue(int value) {
if (isFull()) return false;
items.Add(value);
return true;
}
public bool deQueue() {
if (isEmpty()) return false;
items.RemoveAt(0); // shifts every remaining item left
return true;
}
public int Front() {
if (isEmpty()) return -1;
return items[0];
}
public int Rear() {
if (isEmpty()) return -1;
return items[items.Count - 1];
}
public bool isEmpty() {
return items.Count == 0;
}
public bool isFull() {
return items.Count == capacity;
}
}The Design (General/Specific) infographic is part of Pro
A one-page visual of the pattern: when it applies, the steps and the invariant to keep.
Unlock the infographicSolution pattern
Design (General/Specific)
Part of Design Patterns
Approach 2: Fixed array with head and count (ring buffer)OptimalDesign (General/Specific)
What's slow: deQueue shifts every item, even though only the front position changed. The insight that fixes it: leave the items where they are and move a head index forward. New values go to slot (head + count) mod k, so a slot freed at the front gets reused once the tail wraps around to it. The count tells you when the array is full or empty.
Steps
- Allocate an array of k slots. Set head to 0 and count to 0.
- isEmpty returns count == 0. isFull returns count == k.
- enQueue: if the queue is full, return false. Otherwise compute tail = (head + count) mod k, write the value there, increase count by 1, and return true.
- deQueue: if the queue is empty, return false. Otherwise set head = (head + 1) mod k, decrease count by 1, and return true.
- Front returns data[head]. Rear returns data[(head + count - 1) mod k]. Both return -1 when the queue is empty.
Dry run
The table traces the statement example from the Example section above, with k = 2.
| Step | Call | Returns | head | count | data |
|---|---|---|---|---|---|
| 0 | MyCircularQueue(2) | null | 0 | 0 | [0, 0] |
| 1 | Front() | -1 | 0 | 0 | [0, 0] |
| 2 | Rear() | -1 | 0 | 0 | [0, 0] |
| 3 | isEmpty() | true | 0 | 0 | [0, 0] |
| 4 | isFull() | false | 0 | 0 | [0, 0] |
| 5 | deQueue() | false | 0 | 0 | [0, 0] |
The outputs are [null, -1, -1, true, false, false]. The last call returns false because count is 0, so nothing changes.
Complexity
| Time | O(1) per operation |
|---|---|
| Space | O(k) |
Let k be the capacity. Each method runs a fixed number of comparisons, arithmetic steps, and at most one array access, so each costs O(1). The constructor allocates k slots, and the array never grows, so the space is O(k). The total work for m calls is O(m), because no call touches the rest of the array.
PythonTested in our runner
from typing import List, Optional
class MyCircularQueue:
def __init__(self, k: int):
self.capacity = k
self.data = [0] * k
self.head = 0
self.count = 0
def enQueue(self, value: int) -> bool:
if self.isFull():
return False
# the next free slot is head + count, wrapped by modulo
self.data[(self.head + self.count) % self.capacity] = value
self.count += 1
return True
def deQueue(self) -> bool:
if self.isEmpty():
return False
# only the front moves, no items are copied
self.head = (self.head + 1) % self.capacity
self.count -= 1
return True
def Front(self) -> int:
if self.isEmpty():
return -1
return self.data[self.head]
def Rear(self) -> int:
if self.isEmpty():
return -1
# the last item sits one slot before the next free slot
return self.data[(self.head + self.count - 1) % self.capacity]
def isEmpty(self) -> bool:
return self.count == 0
def isFull(self) -> bool:
return self.count == self.capacityJavaTested in our runner
class MyCircularQueue {
private int[] data;
private int head;
private int count;
private int capacity;
public MyCircularQueue(int k) {
capacity = k;
data = new int[k];
head = 0;
count = 0;
}
public boolean enQueue(int value) {
if (isFull()) return false;
data[(head + count) % capacity] = value;
count++;
return true;
}
public boolean deQueue() {
if (isEmpty()) return false;
head = (head + 1) % capacity;
count--;
return true;
}
public int Front() {
if (isEmpty()) return -1;
return data[head];
}
public int Rear() {
if (isEmpty()) return -1;
return data[(head + count - 1) % capacity];
}
public boolean isEmpty() {
return count == 0;
}
public boolean isFull() {
return count == capacity;
}
}C++Tested in our runner
class MyCircularQueue {
private:
std::vector<int> data;
int head;
int count;
int capacity;
public:
MyCircularQueue(int k) {
capacity = k;
data.assign(k, 0);
head = 0;
count = 0;
}
bool enQueue(int value) {
if (isFull()) return false;
data[(head + count) % capacity] = value;
count++;
return true;
}
bool deQueue() {
if (isEmpty()) return false;
head = (head + 1) % capacity;
count--;
return true;
}
int Front() {
if (isEmpty()) return -1;
return data[head];
}
int Rear() {
if (isEmpty()) return -1;
return data[(head + count - 1) % capacity];
}
bool isEmpty() {
return count == 0;
}
bool isFull() {
return count == capacity;
}
};JavaScriptTested in our runner
var MyCircularQueue = function(k) {
this.capacity = k;
this.data = new Array(k).fill(0);
this.head = 0;
this.count = 0;
};
/**
* @param {number} value
* @return {boolean}
*/
MyCircularQueue.prototype.enQueue = function(value) {
if (this.isFull()) return false;
this.data[(this.head + this.count) % this.capacity] = value;
this.count++;
return true;
};
/**
* @return {boolean}
*/
MyCircularQueue.prototype.deQueue = function() {
if (this.isEmpty()) return false;
this.head = (this.head + 1) % this.capacity;
this.count--;
return true;
};
/**
* @return {number}
*/
MyCircularQueue.prototype.Front = function() {
if (this.isEmpty()) return -1;
return this.data[this.head];
};
/**
* @return {number}
*/
MyCircularQueue.prototype.Rear = function() {
if (this.isEmpty()) return -1;
return this.data[(this.head + this.count - 1) % this.capacity];
};
/**
* @return {boolean}
*/
MyCircularQueue.prototype.isEmpty = function() {
return this.count === 0;
};
/**
* @return {boolean}
*/
MyCircularQueue.prototype.isFull = function() {
return this.count === this.capacity;
};GoTested in our runner
type MyCircularQueue struct {
data []int
head int
count int
capacity int
}
func Constructor(k int) MyCircularQueue {
return MyCircularQueue{data: make([]int, k), head: 0, count: 0, capacity: k}
}
func (this *MyCircularQueue) enQueue(value int) bool {
if this.isFull() {
return false
}
this.data[(this.head+this.count)%this.capacity] = value
this.count++
return true
}
func (this *MyCircularQueue) deQueue() bool {
if this.isEmpty() {
return false
}
this.head = (this.head + 1) % this.capacity
this.count--
return true
}
func (this *MyCircularQueue) Front() int {
if this.isEmpty() {
return -1
}
return this.data[this.head]
}
func (this *MyCircularQueue) Rear() int {
if this.isEmpty() {
return -1
}
return this.data[(this.head+this.count-1)%this.capacity]
}
func (this *MyCircularQueue) isEmpty() bool {
return this.count == 0
}
func (this *MyCircularQueue) isFull() bool {
return this.count == this.capacity
}C#Tested in our runner
public class MyCircularQueue {
private int[] data;
private int head;
private int count;
private int capacity;
public MyCircularQueue(int k) {
capacity = k;
data = new int[k];
head = 0;
count = 0;
}
public bool enQueue(int value) {
if (isFull()) return false;
data[(head + count) % capacity] = value;
count++;
return true;
}
public bool deQueue() {
if (isEmpty()) return false;
head = (head + 1) % capacity;
count--;
return true;
}
public int Front() {
if (isEmpty()) return -1;
return data[head];
}
public int Rear() {
if (isEmpty()) return -1;
return data[(head + count - 1) % capacity];
}
public bool isEmpty() {
return count == 0;
}
public bool isFull() {
return count == capacity;
}
}Common mistakes
Rearreturningdata[(head + count) % k]. That slot is the next free position, not the last item. Use(head + count - 1) % kso Rear reads the newest value.head = head + 1indeQueuewith no modulo. After the last slot, head reaches k andFrontreads past the end of the array. Use(head + 1) % k.if (head == tail)as the only empty or full test. Both states produce the same indices. Track a count, or leave one slot empty and test(tail + 1) % k == headfor full.- Writing before the full check, such as
data[tail] = valuefollowed byif isFull(). When the queue is full, the write overwrites the front item. Check fullness first, then write. return data[head]inFrontwith no empty check. After the last deQueue, the slot still holds an old value, so Front returns a stale number instead of -1. Checkcount == 0first.
Edge cases
- k = 1: the first enQueue succeeds, the second returns false, and modulo by 1 always gives slot 0. After deQueue, enQueue works again.
- Empty queue: Front and Rear return -1, deQueue returns false, isEmpty returns true, and isFull returns false.
- Value 0: 0 is a valid stored value, so Front returning 0 is correct. Decide emptiness from count, never from the returned value.
- Full queue: enQueue returns false and leaves every slot unchanged. Rear still returns the most recent value that was accepted.
- Repeated fill and drain across the array end with k = 3: head cycles 0, 1, 2, 0, and every value comes out in insertion order.
- Maximum load with k = 1000 and 3000 calls: indices stay between 0 and k - 1, and no call reads outside the array.
Follow-ups interviewers ask
- What if the queue should grow when it is full instead of rejecting values?
- Allocate an array of twice the size, copy the items in order starting from head, then set head to 0. Each copy costs O(k), but doubling means the copies happen rarely. The amortized cost of enQueue stays O(1). This also removes the fixed capacity, so isFull would no longer be needed.
- Can you drop the count variable and still tell full from empty?
- Yes. Keep head and tail, and leave one slot always empty. The queue is empty when head equals tail, and full when (tail + 1) mod k equals head. The usable capacity drops to k - 1, so you would allocate k + 1 slots to store k items.
- What if several threads call enQueue and deQueue at the same time?
- A single lock around the methods makes each call atomic, and it is the simplest correct answer. A lock-free ring buffer exists for exactly one producer and one consumer. In that case the producer owns tail and the consumer owns head, and both indices are atomic.
Design Circular Queue FAQ
What is the time complexity of Design Circular Queue?
Every operation runs in O(1) time with the ring buffer, because each call does a fixed number of steps. The array size does not change the step count. The plain list version costs O(k) per deQueue because it shifts items.
Why use a ring buffer for Design Circular Queue?
The problem asks for FIFO order and reuse of slots freed at the front. A head index plus modulo arithmetic makes the array act like a circle, so a dequeue only moves the head. No item is copied, which keeps every call at O(1).
Can Design Circular Queue be solved in O(1) extra space?
Beyond the k slots that hold the values, the solution uses O(1) extra space for head and count. The k slots themselves are required, because the queue must store up to k values. So the total space is O(k), and that cannot be reduced.
Why does the solution need a count variable?
When head equals tail, the queue could be empty or full, and the indices alone cannot tell which. A count stores the answer directly. The tail index is then derived from head and count, so it does not need its own variable.
Is a linked list a valid alternative for Design Circular Queue?
Yes. A circular singly linked list with head, tail, and a size counter also gives O(1) operations. It allocates one node per value, though, so it uses more memory than the fixed array.
Asked at
See which companies ask this — Pro
Related problems
- LRU Cache · same technique: Design (General/Specific)
- Min Stack · same technique: Design (General/Specific)
- Time Based Key-Value Store · same technique: Design (General/Specific)
- Encode and Decode Strings · same technique: Design (General/Specific)
- Detect Squares · same technique: Design (General/Specific)
- Find Median from Data Stream · next harder, same pattern
- Implement Trie (Prefix Tree) · same pattern: Design Patterns
- Design Add and Search Words Data Structure · same pattern: Design Patterns
- Extra Characters in a String · same pattern: Design Patterns
- Design Hit Counter · same pattern: Design Patterns