Design Circular Queue

Build a queue of fixed capacity on an array whose end wraps around to its start.

Write a class DesignCircularQueue for a queue that holds at most k values, where k is given to the constructor. Values leave in the order they arrived, and space freed at the front must be reused for new values. The class supports these operations:

Example 1
Input: DesignCircularQueue(3), enQueue(1), enQueue(2), enQueue(3), enQueue(4), Rear(), isFull(), deQueue(), enQueue(4), Rear()
Output: true, true, true, false, 3, true, true, true, 4
Solution

The Idea

A queue behaves like the line at a ticket window: people join at the back, called the rear, and are served from the front, in the order they came. In Example 1 the line has room for three values, so they can live in an array of three slots, numbered 0, 1 and 2.

Follow the calls. The first three enQueue calls put 1, 2 and 3 into slots 0, 1 and 2. The fourth, enQueue(4), returns false, because every slot is taken. Rear() returns 3, the newest value, and isFull() returns true. Then deQueue() removes 1, the oldest value, which frees slot 0.

Now enQueue(4) must succeed. But where does 4 go? In a line of people, everyone steps forward one place. In the array that means copying 2 into slot 0 and 3 into slot 1, one copy for every value left, on every removal.

There is a cheaper way. Leave 2 and 3 where they are, remember that the front is now slot 1, and put 4 into the free slot 0. The picture shows both moments, with the front marked in teal and the rear in orange.

A queue of three slots. After enQueue 1, 2 and 3 the slots hold 1, 2, 3, with front at slot 0 and rear at slot 2. After deQueue and enQueue(4), 4 wraps around to slot 0: the slots hold 4, 2, 3, front is slot 1 and rear is slot 0.

In the top row, labelled "after enQueue(1), enQueue(2), enQueue(3)", the front is slot 0 and the rear is slot 2. In the bottom row, labelled "after deQueue() and enQueue(4)", the dashed arrow shows 4 going past slot 2 and on to slot 0. The rear now sits left of the front.

Read the bottom row from the front and carry on past slot 2 back to slot 0: 2, 3, 4. That is the order the values arrived in. The array is used as if its two ends were joined into a ring, which is why the queue is called circular. An array used this way is also known as a ring buffer.

Solution Approach

With the values staying in place, three things remain: what the queue tracks besides the array, how a slot number wraps from 2 back to 0, and how to tell empty from full.

What the queue tracks

Which numbers are enough to find every value? Two of them: front, the slot of the oldest value, and size, how many values are stored. In the bottom row of the picture, front is 1 and size is 3, and the values sit in the 3 slots counted from slot 1, wrapping past slot 2. The rear is not stored, because it follows from these two.

Wrapping the slot number

How does slot 3, one past the end, become slot 0? Java's remainder operator % does it: with three slots, 3 % 3 is 0 and 4 % 3 is 1, while 0, 1 and 2 stay as they are.

So the first free slot is (front + size) % k. Before the second enQueue(4), front is 1 and size is 2, and (1 + 2) % 3 = 0, which is where 4 goes. The rear is the slot just before it, (front + size - 1) % k, so afterwards (1 + 3 - 1) % 3 = 0, and Rear() returns 4.

Removing a value moves the front one slot on, again with wrapping: front = (front + 1) % k. Nothing is copied, and the old value stays in its slot until a later enQueue writes over it.

Telling empty from full

Why keep a count at all, instead of a second slot number that marks where the queue ends? Suppose that second number is the first free slot. At the start of Example 1, both are slot 0. After the first three enQueue calls, the first free slot is (0 + 3) % 3 = 0, and front is still 0. The same two numbers then describe an empty queue and a full one.

The count removes that doubt: size == 0 means empty and size == k means full. Front(), Rear() and deQueue() check for empty first, and enQueue checks for full first.

Java Solution

The class has three fields, and each operation is a few lines built on them:

  • data: the k slots, created once in the constructor. Here k is data.length.
  • front: the slot of the oldest value. Front() reads it, and deQueue() moves it one slot on, wrapping.
  • size: how many values are stored. The checks isEmpty() and isFull() compare it with 0 and with data.length.
  • The two slot formulas: enQueue writes into slot (front + size) % data.length, and Rear() reads slot (front + size - 1) % data.length.

The main method runs the calls of Example 1, prints their nine results as one list, and then prints the slots, front and size it ends with. It also tries a queue with k = 1: reading and removing while it is empty, filling it, adding to it while full, and emptying it again.

Java
import java.util.ArrayList;
import java.util.List;

public class DesignCircularQueue {

    private final int[] data;
    private int front = 0;   // slot of the oldest value
    private int size = 0;    // how many values are stored

    public DesignCircularQueue(int k) {
        data = new int[k];
    }

    public boolean enQueue(int value) {
        if (isFull()) {
            return false;
        }
        data[(front + size) % data.length] = value;   // first free slot, wrapping to 0
        size++;
        return true;
    }

    public boolean deQueue() {
        if (isEmpty()) {
            return false;
        }
        front = (front + 1) % data.length;            // the next value becomes the oldest
        size--;
        return true;
    }

    public int Front() {
        return isEmpty() ? -1 : data[front];
    }

    public int Rear() {
        return isEmpty() ? -1 : data[(front + size - 1) % data.length];
    }

    public boolean isEmpty() {
        return size == 0;
    }

    public boolean isFull() {
        return size == data.length;
    }

    public static void main(String[] args) {
        DesignCircularQueue q = new DesignCircularQueue(3);
        List<Object> out = new ArrayList<>();
        out.add(q.enQueue(1));
        out.add(q.enQueue(2));
        out.add(q.enQueue(3));
        out.add(q.enQueue(4));     // full: refused
        out.add(q.Rear());
        out.add(q.isFull());
        out.add(q.deQueue());
        out.add(q.enQueue(4));     // goes into slot 0
        out.add(q.Rear());
        System.out.println(out);
        System.out.println("slots " + java.util.Arrays.toString(q.data)
            + ", front " + q.front + ", size " + q.size + ", Front() " + q.Front());

        DesignCircularQueue one = new DesignCircularQueue(1);
        System.out.println("empty: Front " + one.Front() + ", Rear " + one.Rear()
            + ", deQueue " + one.deQueue() + ", isEmpty " + one.isEmpty());
        System.out.println("k = 1: enQueue(7) " + one.enQueue(7) + ", isFull " + one.isFull()
            + ", Front " + one.Front() + ", Rear " + one.Rear() + ", enQueue(8) " + one.enQueue(8));
        System.out.println("after deQueue " + one.deQueue() + ": isEmpty " + one.isEmpty()
            + ", Rear " + one.Rear());
    }
}

Running it prints:

Output
[true, true, true, false, 3, true, true, true, 4]
slots [4, 2, 3], front 1, size 3, Front() 2
empty: Front -1, Rear -1, deQueue false, isEmpty true
k = 1: enQueue(7) true, isFull true, Front 7, Rear 7, enQueue(8) false
after deQueue true: isEmpty true, Rear -1

The list on the first line, [true, true, true, false, 3, true, true, true, 4], matches the output of Example 1. The second line shows the queue the calls leave behind: slots [4, 2, 3], front 1 and size 3, the bottom row of the picture. Reading slot 1 gives Front() 2.

The line starting with "empty:" shows the queue with one slot before anything is added: Front and Rear return -1 and deQueue returns false. Once 7 is added, it is both the front and the rear, since (0 + 1 - 1) % 1 = 0, and enQueue(8) is refused. On the last line, after 7 is removed, Rear is -1 again.

In Rear(), the - 1 matters. Without it, the index is the first free slot, not the last value. On the full queue of the top row, holding 1, 2 and 3, that index wraps to slot 0, and a quick check of both index formulas on that queue returned 1 instead of 3.

Complexity

No operation moves a stored value, so the work per call does not grow with k.

  • Time: O(1) per operation, because each one computes at most one slot number with a remainder and reads or writes at most that one slot.
  • Space: O(k), because the constructor creates the k slots of data once, and front and size are two more numbers, whatever the sequence of calls.

A queue that also adds and removes at both ends is Design Circular Deque.