Design Circular Deque (LeetCode 641): Solution and Explanation
Build a bounded double-ended queue of capacity k on a fixed array. Values can be added and removed at both ends, inserts fail when the deque is full, deletes fail when it is empty, and every call must run in O(1).
Intuition
A deque on a plain array has a problem at the front: inserting before index 0 would mean shifting every value right. Treating the array as a ring removes that problem, because the slot before 0 is simply slot k - 1.
On a ring the deque is a window of consecutive slots. Two numbers describe it fully: where it starts (front) and how long it is (count). The rear is then (front + count - 1) % k.
Each end now moves by one step. The front end grows by stepping front back and shrinks by stepping it forward. The rear end grows by writing one past the rear and shrinks by lowering count, with front untouched.
Approach: Ring buffer with front and count
- In the constructor allocate an array of
kslots and setfront = 0,count = 0,capacity = k. insertFront(value): ifcount == capacityreturn false. Otherwise setfront = (front - 1 + capacity) % capacity, writevaluethere, incrementcount, return true.insertLast(value): if full return false. Otherwise writevalueat(front + count) % capacity, incrementcount, return true.deleteFront(): ifcount == 0return false. Otherwise setfront = (front + 1) % capacityand decrementcount.deleteLast(): if empty return false, otherwise just decrementcount.getFront()returnsdata[front]andgetRear()returnsdata[(front + count - 1) % capacity], each -1 when empty.isEmpty()iscount == 0andisFull()iscount == capacity.
Step-by-step example
commands = ["MyCircularDeque", "insertLast", "insertLast", "insertFront", "insertFront", "getRear", "isFull", "deleteLast", "insertFront", "getFront"], values = [[3], [1], [2], [3], [4], [], [], [], [4], []]
MyCircularDeque(3)allocates slots 0..2 withfront = 0,count = 0.insertLast(1)writes slot(0 + 0) % 3 = 0andinsertLast(2)writes slot 1. The deque is 1, 2.insertFront(3)stepsfrontfrom 0 back to(0 - 1 + 3) % 3 = 2and writes 3 there. The deque is 3, 1, 2 andcount = 3, soinsertFront(4)returns false.getRear()reads(2 + 3 - 1) % 3 = 1, which is 2.isFull()is true.deleteLast()dropscountto 2, leaving slot 1 stale.insertFront(4)stepsfrontfrom 2 to 1 and overwrites the stale 2 with 4.getFront()reads slot 1, which is 4. Output: [null,true,true,true,false,2,true,true,true,4].
Code: Python, Java, C++
1class MyCircularDeque:
2 def __init__(self, k: int):
3 self.data = [0] * k
4 self.front = 0
5 self.count = 0
6 self.capacity = k
7
8 def insertFront(self, value: int) -> bool:
9 if self.isFull():
10 return False
11 self.front = (self.front - 1 + self.capacity) % self.capacity
12 self.data[self.front] = value
13 self.count += 1
14 return True
15
16 def insertLast(self, value: int) -> bool:
17 if self.isFull():
18 return False
19 self.data[(self.front + self.count) % self.capacity] = value
20 self.count += 1
21 return True
22
23 def deleteFront(self) -> bool:
24 if self.isEmpty():
25 return False
26 self.front = (self.front + 1) % self.capacity
27 self.count -= 1
28 return True
29
30 def deleteLast(self) -> bool:
31 if self.isEmpty():
32 return False
33 self.count -= 1
34 return True
35
36 def getFront(self) -> int:
37 return -1 if self.isEmpty() else self.data[self.front]
38
39 def getRear(self) -> int:
40 return -1 if self.isEmpty() else self.data[(self.front + self.count - 1) % self.capacity]
41
42 def isEmpty(self) -> bool:
43 return self.count == 0
44
45 def isFull(self) -> bool:
46 return self.count == self.capacity1class MyCircularDeque {
2 private int[] data;
3 private int front;
4 private int count;
5 private int capacity;
6
7 public MyCircularDeque(int k) {
8 data = new int[k];
9 front = 0;
10 count = 0;
11 capacity = k;
12 }
13
14 public boolean insertFront(int value) {
15 if (isFull()) {
16 return false;
17 }
18 front = (front - 1 + capacity) % capacity;
19 data[front] = value;
20 count++;
21 return true;
22 }
23
24 public boolean insertLast(int value) {
25 if (isFull()) {
26 return false;
27 }
28 data[(front + count) % capacity] = value;
29 count++;
30 return true;
31 }
32
33 public boolean deleteFront() {
34 if (isEmpty()) {
35 return false;
36 }
37 front = (front + 1) % capacity;
38 count--;
39 return true;
40 }
41
42 public boolean deleteLast() {
43 if (isEmpty()) {
44 return false;
45 }
46 count--;
47 return true;
48 }
49
50 public int getFront() {
51 return isEmpty() ? -1 : data[front];
52 }
53
54 public int getRear() {
55 return isEmpty() ? -1 : data[(front + count - 1) % capacity];
56 }
57
58 public boolean isEmpty() {
59 return count == 0;
60 }
61
62 public boolean isFull() {
63 return count == capacity;
64 }
65}1class MyCircularDeque {
2 vector<int> data;
3 int front;
4 int count;
5 int capacity;
6public:
7 MyCircularDeque(int k) {
8 data = vector<int>(k, 0);
9 front = 0;
10 count = 0;
11 capacity = k;
12 }
13
14 bool insertFront(int value) {
15 if (isFull()) {
16 return false;
17 }
18 front = (front - 1 + capacity) % capacity;
19 data[front] = value;
20 count++;
21 return true;
22 }
23
24 bool insertLast(int value) {
25 if (isFull()) {
26 return false;
27 }
28 data[(front + count) % capacity] = value;
29 count++;
30 return true;
31 }
32
33 bool deleteFront() {
34 if (isEmpty()) {
35 return false;
36 }
37 front = (front + 1) % capacity;
38 count--;
39 return true;
40 }
41
42 bool deleteLast() {
43 if (isEmpty()) {
44 return false;
45 }
46 count--;
47 return true;
48 }
49
50 int getFront() {
51 return isEmpty() ? -1 : data[front];
52 }
53
54 int getRear() {
55 return isEmpty() ? -1 : data[(front + count - 1) % capacity];
56 }
57
58 bool isEmpty() {
59 return count == 0;
60 }
61
62 bool isFull() {
63 return count == capacity;
64 }
65};Time and space complexity
O(1) per operation
Every method does a constant number of comparisons, at most one modulo and at most one array read or write.
O(k)
The array of k slots is allocated once in the constructor and never grows.
Other approaches
Doubly linked list (time O(1) per operation, space O(k))
Keep head and tail pointers plus a size, and link or unlink nodes at either end. It is O(1) per operation too, but it allocates a node per value and gives up the fixed, cache-friendly array.
Front and rear indices with one spare slot (time O(1) per operation, space O(k))
Use an array of k + 1 slots with separate front and rear indices and treat the deque as full when the next rear slot equals front. It avoids a count field at the cost of a wasted slot and trickier conditions.
Common mistakes
- Writing
(front - 1) % kfor insertFront. In Java, C++, C#, JavaScript and Go the remainder of a negative number is negative, so addkfirst:(front - 1 + k) % k. - Computing the rear as
(front + count) % k. That is the next free slot after the rear; the last value is one before it. - Moving
frontin deleteLast. Removing from the rear only shortens the window, so onlycountchanges. - Using
front == rearto decide empty versus full. Both states can look the same with two indices;counttells them apart.
Frequently asked questions
Why does insertFront move front before writing?
front always points at the current first value. The new value has to go in the slot just before it, so front steps back first and the write lands in the new front slot.
Why does deleteLast not touch front?
The window starts at front and has length count. Removing the last value only shortens the window, so decrementing count is enough and the rear moves back automatically.
How is this different from Design Circular Queue?
A queue only inserts at the rear and removes at the front, so front only moves forward. A deque also inserts at the front and removes at the rear, which is why front has to step backward with the + k wrap.
Can I use a built-in deque?
The problem asks you not to. The point is to show you can manage the indices of a fixed ring buffer yourself, which is how real deques such as Python's collections.deque blocks and Java's ArrayDeque work underneath.