Skip to lesson

Build a circular queue

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.

Java
// 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.

  1. Initialize head = 0, tail = 0, and size = 0.
  2. To enqueue, write value at data[tail] and update tail = (tail + 1) % C.
  3. Increment size++.
  4. To dequeue, read value at data[head] and update head = (head + 1) % C.
  5. Decrement size--.

Example 1 · Circular Log Buffer for Recent Events

CircularLogBufferDemo.javaJava
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();    }}
Output
Event B
Event C
Event D

What this code does

  • Event D overwrites Event A in 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

public class Wrap {
public static void main(String[] args) {
int capacity = 3;
int tail = 0;
String slots = "";
for (int i = 1; i <= 5; i++) {
slots = slots + tail + " ";
tail = (tail + 1) % capacity;
}
System.out.println(slots.trim());
}
}

Variables

capacity
3

Output

(nothing printed yet)

Line 3The queue array has 3 slots, numbered 0, 1 and 2.

Step 1 of 14

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

CircularQueueDemo.javaJava
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());    }}
Output
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

SacrificialSlotQueueDemo.javaJava
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));    }}
Output
Offer 300: false
Polled: 100
Offer 300: true

What this code does

  • Allocates capacity + 1 slots so head == tail only 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 == 0 and size == capacity.
  • Sacrificial slot method: leaves one empty slot to disambiguate head and tail.
  • Boundary protection: reject enqueue when full and dequeue when empty.
Tracking an explicit size variable eliminates all pointer ambiguity between full and empty queues.

Next step

Check your understanding

10 quick questions