Design Circular Queue (LeetCode 622): Solution and Explanation
Build a bounded first-in-first-out queue of capacity k on a fixed array. enQueue and deQueue report success or failure, Front and Rear return -1 when the queue is empty, and every operation should run in O(1).
Intuition
A plain array queue that removes from index 0 has to shift everything left, or it keeps drifting right and runs out of room while the front of the array sits unused. The fix is to treat the array as a ring: after the last slot comes slot 0 again.
Once the array is a ring, the queue is just a moving window of consecutive slots. You need to know where the window starts (head) and how long it is (count). The next free slot is (head + count) % k and the rear is one before that.
Removing from the front never erases anything. It only moves head forward by one, so the old value is left behind outside the window and gets overwritten by a later enQueue.
Storing count instead of a separate tail index avoids the classic trap: when head and tail point at the same slot, the queue could be either empty or full. With count the two cases are 0 and k, and you can read them directly.
Approach: Ring buffer with head and count
- In the constructor allocate an array of
kslots, and sethead = 0,count = 0,capacity = k. enQueue(value): ifcount == capacityreturn false. Otherwise writevalueat(head + count) % capacity, incrementcount, return true.deQueue(): ifcount == 0return false. Otherwise sethead = (head + 1) % capacity, decrementcount, return true.Front(): return -1 if empty, elsedata[head].Rear(): return -1 if empty, elsedata[(head + count - 1) % capacity].isEmpty()returnscount == 0andisFull()returnscount == capacity.
Step-by-step example
commands = ["MyCircularQueue","enQueue","enQueue","enQueue","enQueue","Rear","isFull","deQueue","enQueue","Rear"], values = [[3],[1],[2],[3],[4],[],[],[],[4],[]]
MyCircularQueue(3)allocates slots 0..2 withhead = 0,count = 0.enQueue(1),enQueue(2),enQueue(3)write to slots 0, 1 and 2.countis now 3, so the ring is full.enQueue(4)seescount == 3and returns false.Rear()reads slot(0 + 3 - 1) % 3 = 2, which is 3.isFull()returns true.deQueue()movesheadfrom 0 to 1 and dropscountto 2. The 1 still sits in slot 0 but is no longer part of the queue.enQueue(4)writes at(1 + 2) % 3 = 0, wrapping around and overwriting the stale 1.Rear()reads slot(1 + 3 - 1) % 3 = 0, which is 4. Output: [null,true,true,true,false,3,true,true,true,4].
Code: Python, Java, C++
1class MyCircularQueue:
2 def __init__(self, k: int):
3 self.data = [0] * k
4 self.head = 0
5 self.count = 0
6 self.capacity = k
7
8 def enQueue(self, value: int) -> bool:
9 if self.isFull():
10 return False
11 self.data[(self.head + self.count) % self.capacity] = value
12 self.count += 1
13 return True
14
15 def deQueue(self) -> bool:
16 if self.isEmpty():
17 return False
18 self.head = (self.head + 1) % self.capacity
19 self.count -= 1
20 return True
21
22 def Front(self) -> int:
23 return -1 if self.isEmpty() else self.data[self.head]
24
25 def Rear(self) -> int:
26 return -1 if self.isEmpty() else self.data[(self.head + self.count - 1) % self.capacity]
27
28 def isEmpty(self) -> bool:
29 return self.count == 0
30
31 def isFull(self) -> bool:
32 return self.count == self.capacity1class MyCircularQueue {
2 private int[] data;
3 private int head;
4 private int count;
5 private int capacity;
6
7 public MyCircularQueue(int k) {
8 data = new int[k];
9 head = 0;
10 count = 0;
11 capacity = k;
12 }
13
14 public boolean enQueue(int value) {
15 if (isFull()) {
16 return false;
17 }
18 data[(head + count) % capacity] = value;
19 count++;
20 return true;
21 }
22
23 public boolean deQueue() {
24 if (isEmpty()) {
25 return false;
26 }
27 head = (head + 1) % capacity;
28 count--;
29 return true;
30 }
31
32 public int Front() {
33 return isEmpty() ? -1 : data[head];
34 }
35
36 public int Rear() {
37 return isEmpty() ? -1 : data[(head + count - 1) % capacity];
38 }
39
40 public boolean isEmpty() {
41 return count == 0;
42 }
43
44 public boolean isFull() {
45 return count == capacity;
46 }
47}1class MyCircularQueue {
2 vector<int> data;
3 int head;
4 int count;
5 int capacity;
6public:
7 MyCircularQueue(int k) {
8 data = vector<int>(k, 0);
9 head = 0;
10 count = 0;
11 capacity = k;
12 }
13
14 bool enQueue(int value) {
15 if (isFull()) {
16 return false;
17 }
18 data[(head + count) % capacity] = value;
19 count++;
20 return true;
21 }
22
23 bool deQueue() {
24 if (isEmpty()) {
25 return false;
26 }
27 head = (head + 1) % capacity;
28 count--;
29 return true;
30 }
31
32 int Front() {
33 return isEmpty() ? -1 : data[head];
34 }
35
36 int Rear() {
37 return isEmpty() ? -1 : data[(head + count - 1) % capacity];
38 }
39
40 bool isEmpty() {
41 return count == 0;
42 }
43
44 bool isFull() {
45 return count == capacity;
46 }
47};Time and space complexity
O(1) per operation
Every method does a constant number of comparisons, 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
Head and tail with one empty slot (time O(1) per operation, space O(k))
Keep head and tail indices in an array of k + 1 slots and treat the queue as full when (tail + 1) % (k + 1) == head. It avoids a count field at the cost of one wasted slot and slightly trickier conditions.
Singly linked list (time O(1) per operation, space O(k))
Keep pointers to the first and last nodes plus a size. Enqueue appends a node and dequeue drops the first one. It is also O(1), but it allocates a node per value and loses the cache-friendly fixed array that a ring buffer is chosen for.
Common mistakes
- Computing the rear as
(head + count) % k. That is the next free slot; the last value is one before it,(head + count - 1) % k. - Tracking only head and tail. When they meet you cannot tell an empty queue from a full one without an extra flag or count.
- Forgetting the modulo when moving
headindeQueue, which runs past the end of the array after a wrap. - Returning a stale value from
FrontorRearon an empty queue instead of -1. Old values are still physically in the array.
Frequently asked questions
Why does deQueue not clear the slot it removes from?
The slot is already outside the live window once head moves past it, and the next enQueue that reaches it will overwrite it. Clearing it would cost a write and change nothing the caller can observe.
Why store count instead of a tail index?
With head and tail alone, an empty queue and a full queue both have head == tail. A count makes the two cases count == 0 and count == k, and the tail can always be derived as (head + count) % k.
Where are circular queues used in practice?
Anywhere a fixed amount of memory buffers a stream: network and audio buffers, logging ring buffers, producer and consumer queues between threads, and keyboard input buffers.
Can I use a built-in deque?
The problem asks you not to use a built-in queue. The point is to show you can manage the wrap-around indices yourself.