Build a circular queue
28 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)A naive array queue suffers from false overflow when the tail reaches the end of the array. A circular queue uses modulo arithmetic to wrap pointers around and reuse freed slots.
Why linear array queues fail: false overflow
A circular queue stores elements in a fixed array and wraps its front and back indexes around to the start, so no space is wasted.
False overflow is when a linear array queue reports full although slots at the front are free: dequeuing advances front forward, permanently wasting all slots behind it. A circular queue solves this by wrapping front and rear pointers around to index 0 using modulo arithmetic.
// Linear queue: rear only moves forward (0, 1, 2, 3), so it reports "full" at 3// even after dequeues have freed slots 0 and 1rear = rear + 1;// Circular queue: rear wraps back to index 0 (0, 1, 2, 0, 1, ...)rear = (rear + 1) % capacity;Why not shift elements forward whenever front moves? Shifting all elements on every dequeue takes O(n) time, destroying real-time performance. With wraparound, both enqueue and dequeue run in strict constant O(1) time without shifting any elements. Trace a CircularQueue of capacity 3: front = 0, rear = 0, size = 0. enqueue(10): array[0] = 10; rear = (0+1)%3 = 1; size = 1. enqueue(20): array[1] = 20; rear = (1+1)%3 = 2; size = 2. enqueue(30): array[2] = 30; rear = (2+1)%3 = 0; size = 3 (queue full). dequeue(): reads array[0] = 10; front = (0+1)%3 = 1; size = 2. Slot 0 is now reusable! enqueue(40): array[0] = 40; rear = (0+1)%3 = 1; size = 3. Wraparound succeeded!
Edge cases include distinguishing a full queue from an empty queue when front equals rear. Tracking an explicit size variable cleanly separates empty (size == 0) from full (size == capacity).
- Linear queue problem: space at front cannot be reused without shifting.
- Shifting cost: moving n elements takes O(n) time per dequeue.
- Circular queue solution: wraps tail and head back to index 0.
Wrapping pointers with modulo arithmetic
A circular queue stores elements in an array of size C with head and tail pointers.
When inserting an element, advance tail = (tail + 1) % C. When removing an element, advance head = (head + 1) % C.
- Initialize
head = 0,tail = 0, andsize = 0. - To enqueue, write value at
data[tail]and updatetail = (tail + 1) % C. - Increment
size++. - To dequeue, read value at
data[head]and updatehead = (head + 1) % C. - Decrement
size--.
Example 1 · Circular Log Buffer for Recent Events
public class CircularLogBufferDemo { static class LogRing { private final String[] logs; private int writeIndex = 0; private int count = 0;
LogRing(int cap) { logs = new String[cap]; }
void log(String msg) { logs[writeIndex] = msg; writeIndex = (writeIndex + 1) % logs.length; if (count < logs.length) count++; }
void printLogs() { int start = (count < logs.length) ? 0 : writeIndex; for (int i = 0; i < count; i++) { int idx = (start + i) % logs.length; System.out.println(logs[idx]); } } }
public static void main(String[] args) { LogRing ring = new LogRing(3); ring.log("Event A"); ring.log("Event B"); ring.log("Event C"); ring.log("Event D"); ring.printLogs(); }}Event B Event C Event D
What this code does
Event DoverwritesEvent Ain index 0.- The buffer keeps only the 3 most recent log entries.
- Ring buffers operate in fixed O(1) space.
The modulo operator % automatically wraps indices from C - 1 back to 0 without any conditional branches.
Remember:
- Enqueue step:
tail = (tail + 1) % capacity. - Dequeue step:
head = (head + 1) % capacity. - Modulo wrap: index 4 in a size-5 array wraps to index 0 on next increment.
Trace the code
Watch tail wrap around
Variables
- capacity
- 3
Output
(nothing printed yet)Line 3The queue array has 3 slots, numbered 0, 1 and 2.
Distinguishing full from empty states
When head == tail, is the circular queue full or is it empty? Both states align the pointers to the same index.
The cleanest solution maintains an explicit size counter. The queue is empty when size == 0 and full when size == capacity.
Example 2 · Circular Queue Implementation with Explicit Size
public class CircularQueueDemo { static class MyCircularQueue { private final int[] data; private int head = 0; private int tail = 0; private int size = 0;
public MyCircularQueue(int k) { data = new int[k]; }
public boolean enQueue(int value) { if (isFull()) return false; data[tail] = value; tail = (tail + 1) % data.length; size++; return true; }
public boolean deQueue() { if (isEmpty()) return false; head = (head + 1) % data.length; size--; return true; }
public int Front() { return isEmpty() ? -1 : data[head]; } public int Rear() { return isEmpty() ? -1 : data[(tail - 1 + data.length) % data.length]; } public boolean isEmpty() { return size == 0; } public boolean isFull() { return size == data.length; } }
public static void main(String[] args) { MyCircularQueue q = new MyCircularQueue(3); q.enQueue(10); q.enQueue(20); q.enQueue(30); System.out.println("Is full: " + q.isFull()); System.out.println("Dequeued: " + q.deQueue()); q.enQueue(40); System.out.println("Front: " + q.Front()); System.out.println("Rear: " + q.Rear()); }}Is full: true Dequeued: true Front: 20 Rear: 40
What this code does
- Queue fills with 10, 20, 30 at capacity 3.
- Dequeuing 10 frees index 0, allowing 40 to wrap around to index 0.
- Front is now 20 and Rear is 40.
Example 3 · Circular Queue with One Slot Sacrifice
public class SacrificialSlotQueueDemo { static class SacrificialQueue { private final int[] arr; private int head = 0; private int tail = 0;
SacrificialQueue(int capacity) { arr = new int[capacity + 1]; }
boolean offer(int x) { if ((tail + 1) % arr.length == head) return false; arr[tail] = x; tail = (tail + 1) % arr.length; return true; }
int poll() { if (head == tail) return -1; int val = arr[head]; head = (head + 1) % arr.length; return val; } }
public static void main(String[] args) { SacrificialQueue q = new SacrificialQueue(2); q.offer(100); q.offer(200); System.out.println("Offer 300: " + q.offer(300)); System.out.println("Polled: " + q.poll()); System.out.println("Offer 300: " + q.offer(300)); }}Offer 300: false Polled: 100 Offer 300: true
What this code does
- Allocates
capacity + 1slots sohead == tailonly means empty. - Offering 300 initially fails because capacity 2 is reached.
- After polling 100, offering 300 succeeds.
An alternative design reserves one unused array slot, treating (tail + 1) % capacity == head as full.
Two ways to tell full from empty:
- Explicit count method: easiest to read, tracks
size == 0andsize == capacity. - Sacrificial slot method: leaves one empty slot to disambiguate head and tail.
- Boundary protection: reject enqueue when full and dequeue when empty.
size variable eliminates all pointer ambiguity between full and empty queues.Next step
Check your understanding
10 quick questions