#622
Design Circular Queue
Medium Array ring buffer
- Read
- Understand
- Hints
- Approach
- Solution
- Solved
?The problem
Implement a fixed-size circular queue with enQueue, deQueue, Front, Rear, isEmpty and isFull.
This is a short summary in our own words. Read the full statement and examples on LeetCode: open problem ↗
◎Understanding
Really asking: a fixed-size queue that wraps around an array.
Why this works: keep head and count; the next free slot is (head + count) % capacity.
Example: capacity 3: add 1, 2, 3, remove, add 4
[1, 2, 3], head 0remove → head 1add 4 at (1 + 2) % 3 = 0 → [4, 2, 3]
✦Hints open one at a time
Use an array, a head index and a count.
The tail index is (head + count) % capacity.
↗Approach
enQueue writes at (head + count) % cap and increments count. deQueue moves head forward with % cap and decrements count. Rear is at (head + count − 1) % cap.
</>Solution (Java)
class MyCircularQueue {
private final int[] data;
private int head = 0, count = 0;
public MyCircularQueue(int k) {
data = new int[k];
}
public boolean enQueue(int value) {
if (isFull()) return false;
data[(head + count) % data.length] = value; // wrap around
count++;
return true;
}
public boolean deQueue() {
if (isEmpty()) return false;
head = (head + 1) % data.length;
count--;
return true;
}
public int Front() {
return isEmpty() ? -1 : data[head];
}
public int Rear() {
return isEmpty() ? -1 : data[(head + count - 1) % data.length];
}
public boolean isEmpty() {
return count == 0;
}
public boolean isFull() {
return count == data.length;
}
}
!Common mistake
Tracking only head and tail without a count — empty and full look the same.
Complexity
- Time: O(1) per operation.
- Space: O(k).
Topic: Stack & Queue
🎬 Episodes 46–52: video coming soon