Sponsored
Sponsored
This approach involves using a fixed-size array to represent the deque. We'll maintain two indices, front
and rear
, to manage the current front and last positions in the deque. Operations like insertions and deletions are performed by adjusting these indices while ensuring they wrap around using the modulo operation as necessary to remain within the array bounds.
Time Complexity: O(1) for each operation.
Space Complexity: O(k), where k is the capacity of the deque.
1class MyCircularDeque {
2 private int[] data;
3 private int front;
4 private int rear;
5 private int size;
6 private int capacity;
7
8 public MyCircularDeque(int k) {
9 data = new int[k];
10 front = 0;
11 rear = 0;
12 size = 0;
13 capacity = k;
14 }
15
16 public boolean insertFront(int value) {
17 if (isFull()) return false;
18 front = (front - 1 + capacity) % capacity;
19 data[front] = value;
20 size++;
21 return true;
22 }
23
24 public boolean insertLast(int value) {
25 if (isFull()) return false;
26 data[rear] = value;
27 rear = (rear + 1) % capacity;
28 size++;
29 return true;
30 }
31
32 public boolean deleteFront() {
33 if (isEmpty()) return false;
34 front = (front + 1) % capacity;
35 size--;
36 return true;
37 }
38
39 public boolean deleteLast() {
40 if (isEmpty()) return false;
41 rear = (rear - 1 + capacity) % capacity;
42 size--;
43 return true;
44 }
45
46 public int getFront() {
47 if (isEmpty()) return -1;
48 return data[front];
49 }
50
51 public int getRear() {
52 if (isEmpty()) return -1;
53 return data[(rear - 1 + capacity) % capacity];
54 }
55
56 public boolean isEmpty() {
57 return size == 0;
58 }
59
60 public boolean isFull() {
61 return size == capacity;
62 }
63}
The Java solution uses an array and manages the front
and rear
indices to perform the required deque operations. It checks for both capacity and current size to determine the ability to insert or delete elements.
This approach makes use of a doubly linked list to implement the deque. This is particularly effective because it offers dynamic memory usage which can grow or shrink with the number of elements, instead of relying on a pre-allocated fixed-size structure as with arrays.
Time Complexity: O(1) for all operations.
Space Complexity: O(n), where n is the number of elements currently in the deque (potentially more efficient if n is much less than the initial capacity).
1
The Java implementation exploits linked list nodes to hold deque data, which provides benefits of dynamic memory adjustments, ensuring operations like adding or removing at both ends are simple and efficient in terms of pointer rearrangements.