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
creates an empty deque with room forDesignCircularDeque(k) values.k andinsertFront(value) add a value at the front or at the rear. Each returns true, or false if the deque is already full.insertLast(value) anddeleteFront() remove the value at the front or at the rear. Each returns true, or false if the deque is empty.deleteLast() andgetFront() return the value at the front or at the rear, or -1 if the deque is empty.getRear() andisEmpty() say whether the deque holds no values, orisFull() values.k
Example 1
Output, one result per call after the constructor: true, true, true, false, 2, true, true, true, 4
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)insertLast(2)insertFront(3)
The shelf is now full, so the next insertFront(4)getRear()isFull()deleteLast()insertFront(4)getFront()
In code, the shelf becomes an array of kkinsertFront(3)k
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
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()insertFront(4)
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 datakfrontsizesize
Counting slots forward can run past the end of the array. Taking the remainder after dividing by k%k(front + size - 1) % k
Stepping around the ring
Where does each change happen? At the rear, insertLast(front + size) % ksizedeleteFrontfront(front + 1) % ksizedeleteLastsize
The method insertFrontfrontfront - 1%k
Telling full from empty
How do the methods know when to return false or -1? The count in sizesizesizekk
Java Solution
The class keeps three fields, one for each thing the object remembers, plus a helper for printing:
: the ring ofdata slots, made once in the constructor.k : the slot of the first value. The methodfront steps it back withinsertFront , and(front - 1 + data.length) % data.length steps it forward.deleteFront : how many values the deque holds. The methodssize andinsertLast use it to find the rear,getRear only lowers it, anddeleteLast andisEmpty compare it with 0 andisFull .data.length : a small helper for printing, which lists the values from front to rear.contents
The main
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:
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)insertFront(4)deleteLast()insertFront(4)getFront()
The last three lines use a single slot. On the empty deque, getFrontgetRearinsertFront(7)insertLast(8)
Why add data.lengthinsertFrontNegativeModulofront = (front - 1) % data.lengthArrayIndexOutOfBoundsException: 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
, at most one remainder, at most one array read or write, and at most one change tosize orfront .size - Space: O(k), because the constructor makes the array of
slots once, and the only other fields are the two intsk andfront .size
For the version with one open end, where values join at the rear and leave at the front, see