#622

Design Circular Queue

Medium
ArrayLinked ListDesignQueueArrayQueue
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(1)
Space
O(1)
O(n)
💡

Intuition

Time O(1)Space O(n)

The optimal solution uses a fixed-size array and two pointers to efficiently manage the front and rear of the queue. This avoids the need for shifting elements, making operations O(1).

⚙️

Algorithm

5 steps
  1. 1Step 1: Initialize an array of size k, and two pointers: front and rear, both set to -1.
  2. 2Step 2: For enQueue, check if the queue is full. If not, increment rear and add the value. If the queue was empty, set front to 0.
  3. 3Step 3: For deQueue, check if the queue is empty. If not, increment front. If front and rear meet, reset them to -1.
  4. 4Step 4: Implement Front and Rear methods to return the respective values from the queue using the pointers.
  5. 5Step 5: Implement isEmpty and isFull methods to check the status of the queue based on the pointers.
solution.py36 lines
1class MyCircularQueue:
2    def __init__(self, k: int):
3        self.queue = [0] * k
4        self.size = k
5        self.front = self.rear = -1
6
7    def enQueue(self, value: int) -> bool:
8        if self.isFull():
9            return False
10        if self.isEmpty():
11            self.front = self.rear = 0
12        else:
13            self.rear = (self.rear + 1) % self.size
14        self.queue[self.rear] = value
15        return True
16
17    def deQueue(self) -> bool:
18        if self.isEmpty():
19            return False
20        if self.front == self.rear:
21            self.front = self.rear = -1
22        else:
23            self.front = (self.front + 1) % self.size
24        return True
25
26    def Front(self) -> int:
27        return -1 if self.isEmpty() else self.queue[self.front]
28
29    def Rear(self) -> int:
30        return -1 if self.isEmpty() else self.queue[self.rear]
31
32    def isEmpty(self) -> bool:
33        return self.front == -1
34
35    def isFull(self) -> bool:
36        return (self.rear + 1) % self.size == self.front

Complexity note: The time complexity is O(1) for all operations because we are using fixed-size array and pointers to manage the queue without shifting elements. The space complexity is O(n) due to the array storage.

  • 1Circular queues efficiently utilize space by wrapping around.
  • 2Pointers help manage the front and rear without shifting elements.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.