What does it solve?
Implement a queue on a fixed-size array without shifting elements. When the tail reaches the end it wraps around to reuse freed slots at the front, forming a ring.
Key insight: keep a head index (front), a count of items, and capacity k. Enqueue writes at (head + count) % k; dequeue advances head = (head + 1) % k. The modulo is what makes it circular. Empty when count = 0, full when count = k. All ops are O(1).
The core idea
buf[(head+count)%k] = x; count++
dequeue(): if empty → false
head = (head+1)%k; count--
// full: count==k · empty: count==0
Complexity
enqueue, dequeue, front, rear, isEmpty, isFull are all constant time. No element ever moves.
One fixed array of capacity k, reused indefinitely as items cycle through.
Scenarios
Step-by-step table
| Step | op | arg | head | tail | count | result |
|---|
C++ implementation
class MyCircularQueue { vector<int> buf; int head = 0, cnt = 0, k; public: MyCircularQueue(int k) : buf(k), k(k) {} bool enQueue(int x) { if (cnt == k) return false; // full buf[(head + cnt) % k] = x; // wrap with modulo cnt++; return true; } bool deQueue() { if (cnt == 0) return false; // empty head = (head + 1) % k; // advance front cnt--; return true; } int Front() { return cnt == 0 ? -1 : buf[head]; } int Rear() { return cnt == 0 ? -1 : buf[(head + cnt - 1) % k]; } bool isEmpty() { return cnt == 0; } bool isFull() { return cnt == k; } };
My Notes
📝Notes✅
Practice this problem