LeetCode 622 / Classic Circular Queue · Ring Buffer Medium

Design Circular Queue

LC
Practice this on LeetCode. Ring buffers power streaming, producer-consumer buffers, and sliding windows.
Open Problem

A fixed array reused in a circle: head and tail pointers wrap with modulo, so enqueue/dequeue are O(1) with no shifting

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

enqueue(x): if full → false
  buf[(head+count)%k] = x; count++
dequeue(): if empty → false
  head = (head+1)%k; count--
// full: count==k · empty: count==0

Complexity

All operations
O(1)

enqueue, dequeue, front, rear, isEmpty, isFull are all constant time. No element ever moves.

Space complexity
O(k)

One fixed array of capacity k, reused indefinitely as items cycle through.


Scenarios

Live animation — head & tail wrap with modulo
filled slot head (front) tail (next write) dequeued / rejected
Ring buffer (arranged in a circle to show the wrap)
Same array, laid out linearly (index 0 → k−1)
Press Play to run the scenario…
Current op detail
head = — tail = — count = — state = —
Step — of —
head index
—
front slot
tail index
—
(head+count)%k
count
—
of k
last op
—
result
Select a scenario and press Play to start.
✓ Done
SpeedMedium

Step-by-step table

Stepopargheadtailcountresult

C++ implementation

circular_queue.cpp
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