MrainW's Home

All things come to those who wait!

0%

LeetCode 641. Design Circular Deque

Question

Design your implementation of the circular double-ended queue (deque).

Implement the MyCircularDeque class:

  • 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/

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
class MyCircularDeque {
int[] q;
int front = 0, rear = -1, size = 0, capacity;
public MyCircularDeque(int k) {
q = new int[k];
capacity = k;
}

public boolean insertFront(int value) {
if(isFull()) return false;
if(--front < 0) front +=capacity;
q[front] = value;
size++;
if(size == 1) rear = front;
return true;
}

public boolean insertLast(int value) {
if (isFull()) return false;
rear = (rear + 1) % capacity;
q[rear] = value;
size++;
return true;
}

public boolean deleteFront() {
if (isEmpty()) return false;
front = (front + 1) % capacity;
size--;
return true;
}

public boolean deleteLast() {
if(isEmpty()) return false;
if(--rear < 0) rear += capacity;
size--;
return true;
}

public int getFront() {
return isEmpty() ? -1 : q[front];
}

public int getRear() {
return isEmpty() ? -1 : q[rear];
}

public boolean isEmpty() {
return size == 0;
}

public boolean isFull() {
return size == capacity;
}
}

Time Complexity:

MyCircularDeque, O(1). insertFront, O(1). insertLast, O(1). deleteFront, O(1). deleteLast, O(1). getFront, O(1). getRear, O(1). isEmpty(): O(1), isFull(): O(1).

Space: O(k).

Welcome to my other publishing channels