[
design
queue
]
Leetcode 0641 Design Circular Deque
Problem statement
https://leetcode.com/problems/design-circular-deque/
Solution
Very similar to Problem 0622 Design Circular Queue, here we just need to implement two more functions.
Complexity
Time complexity of each operation is O(1)
, space complexity is O(k)
. See problem 0622 for notations of self.end
and self.front
: first one points at the end element and the second points one element after front element.
Code
class MyCircularDeque:
def __init__(self, k: int):
self.CircDueue = [-1]*k
self.k, self.front, self.end = k, 0, 0
def insertFront(self, value):
if self.isFull(): return False
self.CircDueue[self.front % self.k] = value
self.front += 1
return True
def insertLast(self, value):
if self.isFull(): return False
self.end -= 1
self.CircDueue[self.end % self.k] = value
return True
def deleteFront(self):
if self.isEmpty(): return False
self.front -= 1
self.CircDueue[self.front % self.k] = -1
return True
def deleteLast(self):
if self.isEmpty(): return False
self.CircDueue[self.end % self.k] = -1
self.end += 1
return True
def getFront(self):
if self.isEmpty(): return -1
return self.CircDueue[(self.front - 1) % self.k]
def getRear(self):
if self.isEmpty(): return -1
return self.CircDueue[self.end % self.k]
def isEmpty(self):
return self.front == self.end
def isFull(self):
return self.front - self.end == self.k