#641

Design Circular Deque

Medium
ArrayLinked ListDesignQueueCircular ArrayTwo Pointers
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 approach uses a circular array to efficiently manage the front and rear pointers, allowing O(1) time complexity for all operations. This design takes advantage of modular arithmetic to wrap around the array.

⚙️

Algorithm

3 steps
  1. 1Step 1: Initialize an array of size k to represent the deque.
  2. 2Step 2: Use two pointers (front and rear) to track the positions for insertion and deletion.
  3. 3Step 3: Use modular arithmetic to wrap around the pointers when they reach the end of the array.
solution.py49 lines
1class MyCircularDeque:
2    def __init__(self, k: int):
3        self.deque = [0] * k
4        self.max_size = k
5        self.front = 0
6        self.rear = 0
7        self.size = 0
8
9    def insertFront(self, value: int) -> bool:
10        if self.isFull():
11            return False
12        self.front = (self.front - 1 + self.max_size) % self.max_size
13        self.deque[self.front] = value
14        self.size += 1
15        return True
16
17    def insertLast(self, value: int) -> bool:
18        if self.isFull():
19            return False
20        self.deque[self.rear] = value
21        self.rear = (self.rear + 1) % self.max_size
22        self.size += 1
23        return True
24
25    def deleteFront(self) -> bool:
26        if self.isEmpty():
27            return False
28        self.front = (self.front + 1) % self.max_size
29        self.size -= 1
30        return True
31
32    def deleteLast(self) -> bool:
33        if self.isEmpty():
34            return False
35        self.rear = (self.rear - 1 + self.max_size) % self.max_size
36        self.size -= 1
37        return True
38
39    def getFront(self) -> int:
40        return self.deque[self.front] if not self.isEmpty() else -1
41
42    def getRear(self) -> int:
43        return self.deque[(self.rear - 1 + self.max_size) % self.max_size] if not self.isEmpty() else -1
44
45    def isEmpty(self) -> bool:
46        return self.size == 0
47
48    def isFull(self) -> bool:
49        return self.size == self.max_size

Complexity note: The time complexity is O(1) for all operations because we are directly accessing array indices. The space complexity is O(n) due to the storage of elements in the circular array.

  • 1Understanding circular data structures helps in optimizing space and time complexity.
  • 2Using modular arithmetic is crucial for managing indices in circular arrays.

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