Design Circular Deque (LeetCode 641): Solution and Explanation

Medium
Array
Linked List
Design
Queue

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

  1. In the constructor allocate an array of k slots and set front = 0, count = 0, capacity = k.
  2. insertFront(value): if count == capacity return false. Otherwise set front = (front - 1 + capacity) % capacity, write value there, increment count, return true.
  3. insertLast(value): if full return false. Otherwise write value at (front + count) % capacity, increment count, return true.
  4. deleteFront(): if count == 0 return false. Otherwise set front = (front + 1) % capacity and decrement count. deleteLast(): if empty return false, otherwise just decrement count.
  5. getFront() returns data[front] and getRear() returns data[(front + count - 1) % capacity], each -1 when empty. isEmpty() is count == 0 and isFull() is count == capacity.

Step-by-step example

commands = ["MyCircularDeque", "insertLast", "insertLast", "insertFront", "insertFront", "getRear", "isFull", "deleteLast", "insertFront", "getFront"], values = [[3], [1], [2], [3], [4], [], [], [], [4], []]
  1. MyCircularDeque(3) allocates slots 0..2 with front = 0, count = 0.
  2. insertLast(1) writes slot (0 + 0) % 3 = 0 and insertLast(2) writes slot 1. The deque is 1, 2.
  3. insertFront(3) steps front from 0 back to (0 - 1 + 3) % 3 = 2 and writes 3 there. The deque is 3, 1, 2 and count = 3, so insertFront(4) returns false.
  4. getRear() reads (2 + 3 - 1) % 3 = 1, which is 2. isFull() is true. deleteLast() drops count to 2, leaving slot 1 stale.
  5. insertFront(4) steps front from 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.capacity
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(1) per operation

Every method does a constant number of comparisons, at most one modulo and at most one array read or write.

Space

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) % k for insertFront. In Java, C++, C#, JavaScript and Go the remainder of a negative number is negative, so add k first: (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 front in deleteLast. Removing from the rear only shortens the window, so only count changes.
  • Using front == rear to decide empty versus full. Both states can look the same with two indices; count tells 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.