Design Circular Queue
Medium
Subject: Design
Time Complexity
O(1)
Space Complexity
O(K)
Problem Description
Problem Statement
Design your implementation of the circular queue. The circular queue is a linear data structure in which the operations are performed based on FIFO principle, and the last position is connected back to the first position to make a circle. Implement MyCircularQueue with enQueue, deQueue, Front, Rear, isEmpty, isFull.
Example 1:
- Input:
["MyCircularQueue", "enQueue", "enQueue", "enQueue", "enQueue", "Rear", "isFull", "deQueue", "enQueue", "Rear"]\n[[3], [1], [2], [3], [4], [], [], [], [4], []] - Output:
[null, true, true, true, false, 3, true, true, true, 4]
Optimal Solution
PythonApproach: Array with Front and Rear Pointers
Use an array of fixed size k. Maintain front (points to the first element) and rear (points to the last element). Use modulo arithmetic index % k to wrap the pointers around the array boundaries.
class MyCircularQueue:
def __init__(self, k: int):
self.q = [0] * k
self.k = k
self.front = 0
self.rear = -1
self.size = 0
def enQueue(self, value: int) -> bool:
if self.isFull(): return False
self.rear = (self.rear + 1) % self.k
self.q[self.rear] = value
self.size += 1
return True
def deQueue(self) -> bool:
if self.isEmpty(): return False
self.front = (self.front + 1) % self.k
self.size -= 1
return True
def Front(self) -> int:
return -1 if self.isEmpty() else self.q[self.front]
def Rear(self) -> int:
return -1 if self.isEmpty() else self.q[self.rear]
def isEmpty(self) -> bool:
return self.size == 0
def isFull(self) -> bool:
return self.size == self.k