Design Circular Deque — LeetCode 641 Python Solution
MediumDesignQueueArrayLinked List
- Problem
- #641
- Pattern
- Linked List
- Reading time
- 8 min
- Source
- leetcode.com
The problem
Design your implementation of the circular double-ended queue (deque). Implement the MyCircularDeque class: MyCircularDeque(int k) Initializes the deque with a maximum size of k.
Example
- Input
- ["MyCircularDeque", "insertLast", "insertLast", "insertFront", "insertFront", "getRear", "isFull", "deleteLast", "insertFront", "getFront"]
- Output
- [null, true, true, true, false, 2, true, true, true, 4]
- Explanation
- MyCircularDeque myCircularDeque = new MyCircularDeque(3);
Python solution
Python
class MyCircularDeque:
def __init__(self, k: int):
self.k = k + 1
self.data = [0] * self.k
self.front = 0
self.rear = 0
def insertFront(self, value: int) -> bool:
if self.isFull():
return False
self.front = (self.front - 1) % self.k
self.data[self.front] = value
return True
def insertLast(self, value: int) -> bool:
if self.isFull():
return False
self.data[self.rear] = value
self.rear = (self.rear + 1) % self.k
return True
def deleteFront(self) -> bool:
if self.isEmpty():
return False
self.front = (self.front + 1) % self.k
return True
def deleteLast(self) -> bool:
if self.isEmpty():
return False
self.rear = (self.rear - 1) % self.k
return True
def getFront(self) -> int:
return -1 if self.isEmpty() else self.data[self.front]
def getRear(self) -> int:
return -1 if self.isEmpty() else self.data[(self.rear - 1) % self.k]
def isEmpty(self) -> bool:
return self.front == self.rear
def isFull(self) -> bool:
return (self.rear + 1) % self.k == self.frontComplexity
| Measure | Complexity |
|---|---|
| Time | O(V+E) |
| Space | O(V) auxiliary |
Pattern: Linked List
Rewire pointers in place, with a dummy head and a saved next to keep it safe. LeetCode 641. Design Circular Deque is filed here because LeetCode tags it Linked List, which is the vocabulary this hub collects.
The linked list guide has the Python template for the pattern and the 75 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 641. Design Circular Deque?
- LeetCode 641. Design Circular Deque is rated Medium on LeetCode.
- What is the time complexity of LeetCode 641. Design Circular Deque?
- The Python solution on this page runs in O(V+E).
- What is the space complexity of LeetCode 641. Design Circular Deque?
- The Python solution on this page uses O(V) auxiliary space.
- What topics does LeetCode 641. Design Circular Deque cover?
- LeetCode 641. Design Circular Deque is tagged Design, Queue, Array and Linked List on LeetCode.