Leetcode 859 Solution

This article provides solution to leetcode question 859 (design-circular-deque)

https://leetcode.com/problems/design-circular-deque

Solution

class MyCircularDeque:

    def __init__(self, k: int):
        """
        Initialize your data structure here. Set the size of the deque to be k.
        """
        self.a = [0] * k
        self.k = k
        self.head = 0
        self.length = 0

    def insertFront(self, value: int) -> bool:
        """
        Adds an item at the front of Deque. Return true if the operation is successful.
        """
        if self.length == self.k:
            return False

        self.head = (self.head - 1) % self.k
        self.a[self.head] = value
        self.length += 1

        return True

    def insertLast(self, value: int) -> bool:
        """
        Adds an item at the rear of Deque. Return true if the operation is successful.
        """
        if self.length == self.k:
            return False

        self.a[(self.head + self.length) % self.k] = value
        self.length += 1

        return True

    def deleteFront(self) -> bool:
        """
        Deletes an item from the front of Deque. Return true if the operation is successful.
        """
        if self.length == 0:
            return False

        self.head = (self.head + 1) % self.k
        self.length -= 1
        return True

    def deleteLast(self) -> bool:
        """
        Deletes an item from the rear of Deque. Return true if the operation is successful.
        """
        if self.length == 0:
            return False

        self.length -= 1
        return True

    def getFront(self) -> int:
        """
        Get the front item from the deque.
        """
        if self.length == 0:
            return -1
        return self.a[self.head]

    def getRear(self) -> int:
        """
        Get the last item from the deque.
        """
        if self.length == 0:
            return -1
        return self.a[(self.head + self.length - 1) % self.k]

    def isEmpty(self) -> bool:
        """
        Checks whether the circular deque is empty or not.
        """
        return self.length == 0

    def isFull(self) -> bool:
        """
        Checks whether the circular deque is full or not.
        """
        return self.length == self.k


# Your MyCircularDeque object will be instantiated and called as such:
# obj = MyCircularDeque(k)
# param_1 = obj.insertFront(value)
# param_2 = obj.insertLast(value)
# param_3 = obj.deleteFront()
# param_4 = obj.deleteLast()
# param_5 = obj.getFront()
# param_6 = obj.getRear()
# param_7 = obj.isEmpty()
# param_8 = obj.isFull()