💡 Summary: Reusing Empty Front Slots Instead of Hitting a Dead End
In a plain array queue, once the back pointer (rear) reaches the end of the array, you can't add new items—even if you already removed items from the front and left empty spaces behind! That annoying trap is called false overflow. A Circular Queue (often called a ring buffer) fixes this by wrapping the end of the array back around to index 0 using the remainder (modulo) operator: (index + 1) % capacity.
Because it reuses spaces in a neat loop without shifting elements around, a circular queue is great for taking turns in a cycle, buffering audio or network data, and keeping recent readings in a fixed space.
N, a circular queue wraps back to 0 after index N - 1:
- Using a
count(Size) Variable: Keep track of how many items are currently inside (countfrom0tocapacity), and update positions withrear = (rear + 1) % capacityandfront = (front + 1) % capacity. That makes checkingisEmpty()(count == 0) andisFull()(count == capacity) super clear. - One-Slot-Reserved Trick (Without a Counter): Some implementations leave one slot empty and say the queue is full when
(rear + 1) % capacity == front.
| What You Are Comparing | Plain Array Queue | Circular Queue |
|---|---|---|
| Moving Forward | rear + 1 or front + 1 |
(rear + 1) % N or (front + 1) % N |
| Freed Front Slots | Sit unused until the queue resets | Get reused right away as rear wraps around |
enqueue & dequeue |
O(1) until the back hits the end | O(1) even across many wrap-around cycles |
#include
using namespace std;
class CircularQueue {
private:
int* buffer;
int capacity;
int front;
int rear;
int count;
public:
CircularQueue(int cap) {
capacity = cap;
buffer = new int[capacity];
front = 0;
rear = -1;
count = 0;
}
~CircularQueue() {
delete[] buffer;
}
bool isEmpty() const { return count == 0; }
bool isFull() const { return count == capacity; }
void enqueue(int val) {
if (isFull()) {
cout << "Ring Buffer Full! Cannot enqueue " << val << "\n";
return;
}
rear = (rear + 1) % capacity;
buffer[rear] = val;
count++;
cout << "Enqueued " << val << " at index " << rear << " (size=" << count << ")\n";
}
int dequeue() {
if (isEmpty()) {
cout << "Ring Buffer Empty!\n";
return -1;
}
int item = buffer[front];
front = (front + 1) % capacity;
count--;
return item;
}
int peek() const {
return isEmpty() ? -1 : buffer[front];
}
};
int main() {
CircularQueue cq(3);
cq.enqueue(10);
cq.enqueue(20);
cq.enqueue(30);
cout << "Dequeued front: " << cq.dequeue() << "\n"; // Frees index 0
cq.enqueue(40); // Wraps around to index 0!
cout << "Current front: " << cq.peek() << "\n";
return 0;
}
- Circular Linked Queue: In a circular linked list, keeping just a
rearpointer lets you reach the front right away viarear->next, making front removal and back insertion easy without a fixed array size. - Overwriting Ring Buffer: When recording live sensor values or recent logs in a fixed space, if the buffer is full and a new reading arrives, you can overwrite the oldest item at
headand moveheadforward so you always keep the newestNitems.
class Node:
def __init__(self, data):
self.data = data
self.next = None
class CircularLinkedQueue:
def __init__(self):
self.rear = None
def enqueue(self, val):
node = Node(val)
if self.rear is None:
node.next = node
self.rear = node
else:
node.next = self.rear.next # Link new node to the front
self.rear.next = node # Old rear points to new node
self.rear = node # Move rear to the new node
def dequeue(self):
if self.rear is None:
raise IndexError("Circular queue is empty")
front = self.rear.next
if front == self.rear:
self.rear = None
else:
self.rear.next = front.next
return front.data
cq = CircularLinkedQueue()
for task in ["Task_1", "Task_2", "Task_3"]:
cq.enqueue(task)
print("Dequeued:", cq.dequeue())
cq.enqueue("Task_4")
print("Next Dequeued:", cq.dequeue())
print("Next Dequeued:", cq.dequeue())
print("Next Dequeued:", cq.dequeue())
- 1. Taking Turns on a CPU (Round-Robin): Tasks each get a short turn on the CPU; if a task isn't finished yet, it goes to the back of the loop to wait for its next turn.
- 2. Buffering Audio or Video Streams: Media players fill a buffer with incoming data while playing smoothly from the front.
- 3. Incoming & Outgoing Network Data: Network cards and drivers often use ring-shaped buffers to pass packets without pausing or reallocating memory every millisecond.
- 4. Hardware & Microcontroller Input Buffers: Devices with limited memory use fixed-size circular buffers to store incoming signals safely.
- 5. Traffic Signal Cycles: Light phases repeat in a set order around a loop.
from collections import deque
# 1. Taking turns across tasks with a fixed time slice (quantum)
def round_robin_scheduler(processes, quantum):
rq = deque(processes) # Each item: [pid, remaining_time]
time = 0
timeline = []
while rq:
pid, burst = rq.popleft()
run_time = min(burst, quantum)
time += run_time
burst -= run_time
timeline.append(f"{pid}@{time}ms")
if burst > 0:
rq.append([pid, burst]) # Put back at the end to take another turn later
return " -> ".join(timeline)
tasks = [["P1", 10], ["P2", 4], ["P3", 7]]
print("1. Round-Robin Execution (quantum=4ms):")
print(" ", round_robin_scheduler(tasks, quantum=4))
- 6. Keeping the Last N Sensor Readings: A weather or IoT device can keep just the latest few readings in a fixed space without growing forever.
- 7. Rotating Turns in Multiplayer Games: Turns move from one player to the next and wrap back to the first player.
- 8. Reusing a Pool of Connections or Workers: When a worker finishes a job, it can go back into a pool to be reused.
- 9. Keeping Recent Logs in Memory: Apps sometimes keep only the last few hundred log messages in a rolling buffer for quick viewing.
- 10. Items Moving on a Loop / Carousel: Positions around a loop map naturally to remainder (modulo) math.
# 6. Keeping only the latest 4 temperature readings in a fixed-size ring
class SensorRingBuffer:
def __init__(self, capacity):
self.capacity = capacity
self.buf = [None] * capacity
self.head = 0
self.size = 0
def record(self, reading):
idx = (self.head + self.size) % self.capacity
if self.size == self.capacity:
self.buf[self.head] = reading
self.head = (self.head + 1) % self.capacity
else:
self.buf[idx] = reading
self.size += 1
def latest_readings(self):
return [self.buf[(self.head + i) % self.capacity] for i in range(self.size)]
sensor = SensorRingBuffer(4)
for temp in [28.1, 28.4, 29.0, 29.5, 30.2, 30.8]:
sensor.record(temp)
print("6. Latest 4 Sensor Readings:", sensor.latest_readings())
- Don't forget
% capacity: When movingfrontorrearforward, always wrap with% capacityso it loops back to0instead of going out of bounds. - Watch out for the "Full vs. Empty" confusion: If you don't track
count(or reserve one slot),front == rearcan look the same when empty and when full. - Know why it exists: A circular queue is the go-to fix when you want a fixed-size array queue that reuses freed front slots without false overflow.
checkpoints = [
"Wrap Around with %: next_idx = (idx + 1) % capacity keeps indices inside bounds.",
"No False Overflow: Empty slots at the front get reused as rear wraps around.",
"Track Size Clearly: Using a count variable makes empty and full checks easy to read."
]
for item in checkpoints:
print("*", item)