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 ofk
.boolean insertFront()
Adds an item at the front of Deque. Returnstrue
if the operation is successful, orfalse
otherwise.boolean insertLast()
Adds an item at the rear of Deque. Returnstrue
if the operation is successful, orfalse
otherwise.boolean deleteFront()
Deletes an item from the front of Deque. Returnstrue
if the operation is successful, orfalse
otherwise.boolean deleteLast()
Deletes an item from the rear of Deque. Returnstrue
if the operation is successful, orfalse
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()
Returnstrue
if the deque is empty, orfalse
otherwise.boolean isFull()
Returnstrue
if the deque is full, orfalse
otherwise.
Examples
Example 1:
|
|
Solution
Video explanation
Here is the video explaining the methods in detail. Please check it out:
Method 1 - Using Array
Code
|
|
|
|
Complexity
- ⏰ Time complexity:
O(1)
, - All operations (insertFront
,insertLast
,deleteFront
,deleteLast
,getFront
,getRear
,isEmpty
, andisFull
) areO(1)
because they involve a fixed amount of work regardless of the size of the deque. - 🧺 Space complexity:
O(k)
, wherek
is the size of the deque. This space is used to store the elements in the circular array.
Method 2 - Using Double Linked List
Code
|
|
|
|
Complexity
- ⏰ Time complexity:
O(1)
, - All operations (insertFront
,insertLast
,deleteFront
,deleteLast
,getFront
,getRear
,isEmpty
, andisFull
) areO(1)
because they involve a fixed amount of work regardless of the size of the deque. - 🧺 Space complexity:
O(k)
, wherek
is the size of the deque. This space is used to store the elements in the circular array.