Skip to content

Instantly share code, notes, and snippets.

@izeigerman
Created May 16, 2019 23:04
Show Gist options
  • Save izeigerman/6588d27e93a6e18510e3587f12a11a9f to your computer and use it in GitHub Desktop.
Save izeigerman/6588d27e93a6e18510e3587f12a11a9f to your computer and use it in GitHub Desktop.
class MyCircularDeque:
def __init__(self, k: int):
"""
Initialize your data structure here. Set the size of the deque to be k.
"""
self._capacity = k
self._size = 0
self._queue = [None] * self._capacity
self._head = None
self._tail = None
def _check_bounderies(self, index):
if index < 0:
return self._capacity - 1
elif index >= self._capacity:
return 0
return index
def _set_tail(self, new_tail):
self._tail = self._check_bounderies(new_tail)
def _set_head(self, new_head):
self._head = self._check_bounderies(new_head)
def insertFront(self, value: int) -> bool:
"""
Adds an item at the front of Deque. Return true if the operation is successful.
"""
if not self.isFull():
if self._head is None or self._tail is None:
self._head = 0
self._tail = 0
else:
self._set_head(self._head - 1)
self._queue[self._head] = value
self._size += 1
return True
else:
return False
def insertLast(self, value: int) -> bool:
"""
Adds an item at the rear of Deque. Return true if the operation is successful.
"""
if not self.isFull():
if self._head is None or self._tail is None:
self._head = 0
self._tail = 0
else:
self._set_tail(self._tail + 1)
self._queue[self._tail] = value
self._size += 1
return True
else:
return False
def deleteFront(self) -> bool:
"""
Deletes an item from the front of Deque. Return true if the operation is successful.
"""
if not self.isEmpty():
self._queue[self._head] = None
self._set_head(self._head + 1)
self._size -= 1
return True
else:
return False
def deleteLast(self) -> bool:
"""
Deletes an item from the rear of Deque. Return true if the operation is successful.
"""
if not self.isEmpty():
self._queue[self._tail] = None
self._set_tail(self._tail - 1)
self._size -= 1
return True
else:
return False
def getFront(self) -> int:
"""
Get the front item from the deque.
"""
if not self.isEmpty():
return self._queue[self._head]
else:
return -1
def getRear(self) -> int:
"""
Get the last item from the deque.
"""
if not self.isEmpty():
return self._queue[self._tail]
else:
return -1
def isEmpty(self) -> bool:
"""
Checks whether the circular deque is empty or not.
"""
return self._size == 0
def isFull(self) -> bool:
"""
Checks whether the circular deque is full or not.
"""
return self._size == self._capacity
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment