622. Design Circular Queue
Asked at 20Apple63Amazon38Microsoft38Meta26Google26Bloomberg22Optiver97Nvidia55Cloudflare100Splunk100Tesla82Datadog72Qualcomm68Waymo58Coinbase51Rubrik50Applied Intuition48Citadel47Snowflake39Goldman Sachs21
Problem
Design MyCircularQueue(k), a fixed-size ring buffer with enQueue(value) and deQueue() (each returns whether it succeeded), Front() and Rear() (−1 when empty), isEmpty() and isFull(). Don't use a built-in queue.
Example: k = 3: enQueue 1, 2, 3 → true, enQueue 4 → false, Rear() = 3, deQueue() → true, enQueue 4 → true, Rear() = 4
Fixed array + head index + count. Tail index = (head + count − 1) % k. No need to waste a slot when you track count.
Complexity: O(1) per operation.
class MyCircularQueue:
def __init__(self, k: int):
self.a, self.head, self.n = [0] * k, 0, 0
def enQueue(self, value: int) -> bool:
if self.isFull():
return False
self.a[(self.head + self.n) % len(self.a)] = value
self.n += 1
return True
def deQueue(self) -> bool:
if self.isEmpty():
return False
self.head = (self.head + 1) % len(self.a)
self.n -= 1
return True
def Front(self) -> int:
return -1 if self.isEmpty() else self.a[self.head]
def Rear(self) -> int:
return -1 if self.isEmpty() else self.a[(self.head + self.n - 1) % len(self.a)]
def isEmpty(self) -> bool:
return self.n == 0
def isFull(self) -> bool:
return self.n == len(self.a)
cq = MyCircularQueue(3)
assert cq.enQueue(1) and cq.enQueue(2) and cq.enQueue(3) and not cq.enQueue(4)
assert cq.Rear() == 3 and cq.isFull() and cq.deQueue() and cq.enQueue(4) and cq.Rear() == 4
class MyCircularQueue {
private final int[] a;
private int head = 0, n = 0;
public MyCircularQueue(int k) { a = new int[k]; }
public boolean enQueue(int value) {
if (isFull()) return false;
a[(head + n++) % a.length] = value;
return true;
}
public boolean deQueue() {
if (isEmpty()) return false;
head = (head + 1) % a.length;
n--;
return true;
}
public int Front() { return isEmpty() ? -1 : a[head]; }
public int Rear() { return isEmpty() ? -1 : a[(head + n - 1) % a.length]; }
public boolean isEmpty() { return n == 0; }
public boolean isFull() { return n == a.length; }
}
type MyCircularQueue struct {
a []int
head, n int // index of the front, number of items
}
func Constructor(k int) MyCircularQueue {
return MyCircularQueue{a: make([]int, k)}
}
func (this *MyCircularQueue) EnQueue(value int) bool {
if this.IsFull() {
return false
}
this.a[(this.head+this.n)%len(this.a)] = value
this.n++
return true
}
func (this *MyCircularQueue) DeQueue() bool {
if this.IsEmpty() {
return false
}
this.head = (this.head + 1) % len(this.a)
this.n--
return true
}
func (this *MyCircularQueue) Front() int {
if this.IsEmpty() {
return -1
}
return this.a[this.head]
}
func (this *MyCircularQueue) Rear() int {
if this.IsEmpty() {
return -1
}
return this.a[(this.head+this.n-1)%len(this.a)]
}
func (this *MyCircularQueue) IsEmpty() bool {
return this.n == 0
}
func (this *MyCircularQueue) IsFull() bool {
return this.n == len(this.a)
}