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.
1public class 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 bool 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 bool 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 bool DeleteFront() {
33 if (IsEmpty()) return false;
34 front = (front + 1) % capacity;
35 size--;
36 return true;
37 }
38
39 public bool 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 bool IsEmpty() {
57 return size == 0;
58 }
59
60 public bool IsFull() {
61 return size == capacity;
62 }
63}
The C# solution implements the circular deque using an array, managing the front
and rear
positions using indices and supports circular adjustments when reaching the end of the array.
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
Using a linked list in C allows dynamic memory management for each element in the deque. Nodes are created or deleted dynamically, with pointers next
and prev
facilitating easy front and rear operations.