641. Design Circular Deque

Medium

Problem:

Design a circular deque that provides the following operations.

  • MyCircularDeque(int k) Initializes the deque with a maximum size of k.

  • boolean insertFront() Adds an item at the front of Deque. Returns true if the operation is successful, or false otherwise.

  • boolean insertLast() Adds an item at the rear of Deque. Returns true if the operation is successful, or false otherwise.

  • boolean deleteFront() Deletes an item from the front of Deque. Returns true if the operation is successful, or false otherwise.

  • boolean deleteLast() Deletes an item from the rear of Deque. Returns true if the operation is successful, or false otherwise.

  • int getFront() Returns the front item from the Deque. Returns -1 if the deque is empty.

  • int getRear() Returns the last item from Deque. Returns -1 if the deque is empty.

  • boolean isEmpty() Returns true if the deque is empty, or false otherwise.

  • boolean isFull() Returns true if the deque is full, or false otherwise.

https://leetcode.com/problems/design-circular-deque/arrow-up-right

Solution:

Array

Solving this problem with an array leverages the benefits of a circular structure.

  • front_ptr points to the first element in the deque.

  • rear_ptr points to the position where the next element will be inserted at the end.

Doubly Linked List

They are simply implemented through a doubly linked list for the sake of the solution. However, in reality, Python's deque implementation is based on a doubly linked list.

  1. The reason for implementing in a circular fashion is with the intent to connect the tail and head to utilize the empty space at the front when the space gets filled from the back. However, since linked lists inherently don't have the concept of "empty space", the circular structure is meaningless.

  2. The operations of a deque only extract values from the very beginning and the very end. There's no operation to extract the value following the very end, so there's also no need for them to be interconnected.

Note: Based on the PEP 8 naming convention, the method name was set to _add() and _del() with a single underscore (_) at the beginning to signify that it is used internally.

Last updated