Design Circular Deque

Add and remove values at both ends of a fixed-size deque without moving any stored value.

Design a deque with room for at most k values. A deque, short for double-ended queue and said "deck", is a line of values that can grow or shrink at both ends, called the front and the rear. The class needs these methods:

Example 1
Input: DesignCircularDeque(3), insertLast(1), insertLast(2), insertFront(3), insertFront(4), getRear(), isFull(), deleteLast(), insertFront(4), getFront()
Output, one result per call after the constructor: true, true, true, false, 2, true, true, true, 4
Solution

The Idea

Picture a short shelf with room for three jars, where you may put a jar on or take one off at either end. A deque with room for 3 values does the same with numbers. Follow Example 1 on that shelf. The calls insertLast(1) and insertLast(2) give 1, 2 from front to rear. Then insertFront(3) puts 3 ahead of them: 3, 1, 2.

The shelf is now full, so the next insertFront(4) returns false. The rear value is 2, so getRear() returns 2, and isFull() returns true. Next, deleteLast() takes the 2 away, leaving 3, 1. Then insertFront(4) works, the deque reads 4, 3, 1, and getFront() returns 4.

In code, the shelf becomes an array of k places, which we will call slots, numbered 0 to k - 1. The obvious layout keeps the front value in slot 0. But then insertFront(3) has to shift 1 and 2 one slot to the right to make room in slot 0. With a large k, every insert at the front would move almost every stored value. Can the values stay where they are?

They can, if the front is allowed to move instead. Treat the array as a ring: the slot before slot 0 is the last slot, slot k - 1. An insert at the front then writes into the slot just before the current front, wherever that is. The picture follows the calls of Example 1 on the three slots.

A deque of capacity 3 in slots 0, 1 and 2. After insertLast(1) and insertLast(2) the slots hold 1, 2 and empty, with front at slot 0. insertFront(3) wraps front back to slot 2. After deleteLast() and insertFront(4) the slots hold 1, 4, 3, with front at slot 1 and rear at slot 0, so the deque reads 4, 3, 1.

In the top row, labelled "after insertLast(1) and insertLast(2)", front points at slot 0 and rear at slot 1. In the row labelled "after insertFront(3)", there is no slot before slot 0, so front wraps around to slot 2 and 3 is written there. Reading from front around the ring gives 3, 1, 2, and nothing moved.

The bottom row shows the last calls. First deleteLast() left the 2 in slot 1, but no longer counted it as part of the deque. Then insertFront(4) stepped front back from slot 2 to slot 1 and wrote 4 over the old 2. The slots hold 1, 4, 3, yet the deque reads 4, 3, 1, because reading starts at front.

So two numbers describe the whole deque: the slot where the front is, and how many values there are, shown as size in the picture. An array used this way, where the end wraps around to the start, is called a circular buffer, which is where the problem gets its name.

Solution Approach

Three decisions remain: what the object remembers, how the front and the rear step around the ring, and how to tell a full deque from an empty one.

What the object remembers

Which fields does the class need? An array data of k slots, the slot of the first value in front, and the number of values in size. A separate index for the rear is not needed, because the rear is size - 1 slots after the front.

Counting slots forward can run past the end of the array. Taking the remainder after dividing by k, written % in Java, brings the count back into slots 0 to k - 1. The rear slot is (front + size - 1) % k. In the bottom row of the picture, front is 1 and size is 3, so the rear is (1 + 3 - 1) % 3, which is 3 % 3 = 0, the slot labelled rear.

Stepping around the ring

Where does each change happen? At the rear, insertLast writes into the slot just after the rear value, (front + size) % k, and adds one to size. At the front, deleteFront moves front one slot forward with (front + 1) % k and takes one from size. The method deleteLast only takes one from size: the old value stays in its slot, uncounted, until a later insert writes over it.

The method insertFront moves front one slot back, and that is where the ring needs care. From slot 0, front - 1 is -1. In Java, the result of % takes the sign of the number on its left, so -1 % 3 is -1, not 2. Adding k before taking the remainder keeps the number from going below zero: (0 - 1 + 3) % 3 is 2, the wrap shown in the row labelled "after insertFront(3)".

Telling full from empty

How do the methods know when to return false or -1? The count in size answers it directly: the deque is empty when size is 0 and full when size is k. Slot indexes alone could not tell. An index for the front and another for the slot after the rear would point at the same slot in both cases, once all k slots are used and once none are.

Java Solution

The class keeps three fields, one for each thing the object remembers, plus a helper for printing:

  • data: the ring of k slots, made once in the constructor.
  • front: the slot of the first value. The method insertFront steps it back with (front - 1 + data.length) % data.length, and deleteFront steps it forward.
  • size: how many values the deque holds. The methods insertLast and getRear use it to find the rear, deleteLast only lowers it, and isEmpty and isFull compare it with 0 and data.length.
  • contents: a small helper for printing, which lists the values from front to rear.

The main method runs the calls of Example 1 on a deque of capacity 3, printing each result next to the values or the front slot, and then tries a deque of capacity 1, empty, with one value, and after a delete.

Java
public class DesignCircularDeque {

    private final int[] data;   // the ring of k slots
    private int front = 0;      // slot of the first value
    private int size = 0;       // how many values the deque holds

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

    public boolean insertFront(int value) {
        if (isFull()) {
            return false;
        }
        front = (front - 1 + data.length) % data.length;  // one slot back, 0 wraps to k - 1
        data[front] = value;
        size++;
        return true;
    }

    public boolean insertLast(int value) {
        if (isFull()) {
            return false;
        }
        data[(front + size) % data.length] = value;       // the slot just after the rear
        size++;
        return true;
    }

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

    public boolean deleteLast() {
        if (isEmpty()) {
            return false;
        }
        size--;                                           // the rear value is no longer counted
        return true;
    }

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

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

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

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

    // front to rear, for printing
    String contents() {
        StringBuilder sb = new StringBuilder("[");
        for (int i = 0; i < size; i++) {
            if (i > 0) {
                sb.append(", ");
            }
            sb.append(data[(front + i) % data.length]);
        }
        return sb.append("]").toString();
    }

    public static void main(String[] args) {
        DesignCircularDeque d = new DesignCircularDeque(3);
        System.out.println("insertLast(1)  " + d.insertLast(1) + "   " + d.contents());
        System.out.println("insertLast(2)  " + d.insertLast(2) + "   " + d.contents());
        System.out.println("insertFront(3) " + d.insertFront(3) + "   front slot " + d.front);
        System.out.println("insertFront(4) " + d.insertFront(4) + "  " + d.contents());
        System.out.println("getRear()      " + d.getRear());
        System.out.println("isFull()       " + d.isFull());
        System.out.println("deleteLast()   " + d.deleteLast() + "   " + d.contents());
        System.out.println("insertFront(4) " + d.insertFront(4) + "   front slot " + d.front);
        System.out.println("getFront()     " + d.getFront() + "      " + d.contents());

        DesignCircularDeque one = new DesignCircularDeque(1);
        System.out.println("k = 1, empty:  " + one.getFront() + " " + one.getRear()
                + " " + one.deleteFront() + " " + one.deleteLast());
        System.out.println("k = 1, add 7:  " + one.insertFront(7) + " " + one.getFront()
                + " " + one.getRear() + " " + one.insertLast(8));
        System.out.println("k = 1, delete: " + one.deleteLast() + " " + one.isEmpty());
    }
}

Running it prints:

Output
insertLast(1)  true   [1]
insertLast(2)  true   [1, 2]
insertFront(3) true   front slot 2
insertFront(4) false  [3, 1, 2]
getRear()      2
isFull()       true
deleteLast()   true   [3, 1]
insertFront(4) true   front slot 1
getFront()     4      [4, 3, 1]
k = 1, empty:  -1 -1 false false
k = 1, add 7:  true 7 7 false
k = 1, delete: true true

The first nine lines repeat the output of Example 1: true, true, true, false, 2, true, true, true, 4. The line for insertFront(3) shows front slot 2, the wrap from slot 0. The refused insertFront(4) leaves the deque at [3, 1, 2]. After deleteLast() it reads [3, 1], and the second insertFront(4) puts front at slot 1, so getFront() returns 4 and the deque reads [4, 3, 1], as in the bottom row of the picture.

The last three lines use a single slot. On the empty deque, getFront and getRear both return -1 and both deletes return false. After insertFront(7), front and rear are the same slot, so both getters return 7, and insertLast(8) returns false. Deleting the 7 leaves the deque empty again.

Why add data.length in insertFront? A separate test program, NegativeModulo, made the first front insert on an empty array of 3 slots with front = (front - 1) % data.length instead. It printed -1 for -1 % 3 and then stopped with ArrayIndexOutOfBoundsException: Index -1 out of bounds for length 3.

Complexity

No method loops over the stored values, and no value is ever moved, so each call costs the same however full the deque is.

  • Time: O(1) per operation, because each method does one check of size, at most one remainder, at most one array read or write, and at most one change to front or size.
  • Space: O(k), because the constructor makes the array of k slots once, and the only other fields are the two ints front and size.

For the version with one open end, where values join at the rear and leave at the front, see Design Circular Queue.