5.6More Queues and Applications
Deque: the double-ended queue
In a queue elements enter at the rear and leave at the front. In a stack they enter and leave at the same end. A deque (double-ended queue) combines the two: you can add and remove at both ends. In this lesson you build a deque on the array of a circular queue, and all four operations take O(1).
- The four deque operations, and why a stack and a queue are special ways of using it
- How
frontsteps back and wraps to the end when you push at the front - How to work out the position of the last element from
frontandcount
1Idea
A deque has four basic operations: push at the front, push at the back, pop from the front, pop from the back. Depending on which ones you use, the deque behaves like a different structure:
| Operations you use | Behaviour |
|---|---|
| Push back + pop front | Queue (FIFO) |
| Push back + pop back | Stack (LIFO) |
| All four | Double-ended queue |
To build it on an array you use the idea of the circular queue: when the index reaches the end of the array, it goes back to the start. Here you need one more thing: pushing at the front moves front one step back. If front is 0, one step back means wrapping to the last cell of the array. (front - 1 + CAPACITY) % CAPACITY does that.
This lesson does not keep a separate rear. Since the element count count is known, the last element is at (front + count - 1) % CAPACITY, and the cell for a push at the back is (front + count) % CAPACITY. So a push at the front never has to update two indexes together, and an empty deque takes a push at either end just as safely.
In C the % operator gives a negative result for a negative number: -1 % 5 is -1 in C. That is why CAPACITY is added before stepping back. In Python -1 % 5 is already 4, and the Python code uses that. Java behaves like C.
Libraries use deques a lot: java.util.ArrayDeque in Java and collections.deque in Python. Both keep a circular array inside and grow when it is full. This site uses them too in the stack and queue applications.
2Step by step
The capacity is 5. The deque holds 3 and 8, and front is 0. First 5 is pushed at the front and front wraps to the end. Then 6 is pushed at the back, and one element leaves from each end.
- Start.
frontis 0 andcountis 2. The order is 3, 8. - pushFront(5). First the full check:
countis 2, the capacity is 5. There is room. frontsteps back: (0 - 1 + 5) % 5 = 4. It wrapped from the start of the array to the end.- 5 is written to
items[4]. The front element is now 5. countbecomes 3. The order is read starting atfront, not from left to right: 5, 3, 8.- pushBack(6). The cell for the new last element is (4 + 3) % 5 = 2. 6 is written there and
countbecomes 4. The order: 5, 3, 8, 6. - popBack(). The last element is at (4 + 4 - 1) % 5 = 2. 6 is returned and
countbecomes 3. The cell still holds 6, but it is no longer part of the deque. - popFront(). The 5 in
items[4]is returned,frontbecomes (4 + 1) % 5 = 0, andcountis 2. The deque is 3, 8 again.
#define CAPACITY 5 struct Deque { int items[CAPACITY]; int front; // index of the front element int count; // number of elements}; void create(struct Deque* d) { d->front = 0; d->count = 0;} bool isEmpty(struct Deque* d) { return d->count == 0; }bool isFull(struct Deque* d) { return d->count == CAPACITY; } bool pushFront(struct Deque* d, int value) { if (isFull(d)) return false; d->front = (d->front - 1 + CAPACITY) % CAPACITY; // step back, wrap to the end if needed d->items[d->front] = value; d->count++; return true;} bool pushBack(struct Deque* d, int value) { if (isFull(d)) return false; d->items[(d->front + d->count) % CAPACITY] = value; // the cell after the last one d->count++; return true;} bool popFront(struct Deque* d, int* value) { if (isEmpty(d)) return false; *value = d->items[d->front]; d->front = (d->front + 1) % CAPACITY; d->count--; return true;} bool popBack(struct Deque* d, int* value) { if (isEmpty(d)) return false; *value = d->items[(d->front + d->count - 1) % CAPACITY]; d->count--; return true;}class CircularDeque { int[] items; int front = 0; // index of the front element int count = 0; // number of elements CircularDeque(int capacity) { items = new int[capacity]; } boolean isEmpty() { return count == 0; } boolean isFull() { return count == items.length; } void pushFront(int value) { if (isFull()) throw new IllegalStateException("deque is full"); front = (front - 1 + items.length) % items.length; // step back, wrap to the end if needed items[front] = value; count++; } void pushBack(int value) { if (isFull()) throw new IllegalStateException("deque is full"); items[(front + count) % items.length] = value; // the cell after the last one count++; } int popFront() { if (isEmpty()) throw new IllegalStateException("deque is empty"); int value = items[front]; front = (front + 1) % items.length; count--; return value; } int popBack() { if (isEmpty()) throw new IllegalStateException("deque is empty"); int value = items[(front + count - 1) % items.length]; count--; return value; }}class CircularDeque: def __init__(self, capacity): self.items = [None] * capacity self.front = 0 # index of the front element self.count = 0 # number of elements def is_empty(self): return self.count == 0 def is_full(self): return self.count == len(self.items) def push_front(self, value): if self.is_full(): raise IndexError("deque is full") self.front = (self.front - 1) % len(self.items) # in Python -1 % 5 == 4 self.items[self.front] = value self.count += 1 def push_back(self, value): if self.is_full(): raise IndexError("deque is full") self.items[(self.front + self.count) % len(self.items)] = value self.count += 1 def pop_front(self): if self.is_empty(): raise IndexError("deque is empty") value = self.items[self.front] self.front = (self.front + 1) % len(self.items) self.count -= 1 return value def pop_back(self): if self.is_empty(): raise IndexError("deque is empty") value = self.items[(self.front + self.count - 1) % len(self.items)] self.count -= 1 return valueThe snippets focus on the operation in this lesson. The C examples need stdlib.h.
3Complexity
Each of the four operations is a few arithmetic steps and one read or write. No element is shifted.
The elements live in an array set aside up front; the operations ask for no new memory.
To build a deque with a linked list you need a doubly linked list. In a singly linked list, popping from the back means walking from the head to find the node before the last one, which takes O(n).
4Common mistake
The most common mistake in C or Java is forgetting to add CAPACITY when stepping back:
d->front = (d->front - 1) % CAPACITY; // -1 when front is 0When front is 0 the result is -1, and the value is written to items[-1]. C does not stop this and corrupts the memory before the array; Java throws an ArrayIndexOutOfBoundsException. Another mistake is decreasing count before working out the index in popBack: then the element before the last one is read.
5Try it
An empty deque with capacity 5 has front = 0. You call pushFront(1), then pushFront(2). What is front, and which cell holds 2?
The answer is B. The first push sets front to (0 - 1 + 5) % 5 = 4 and writes 1 there. The second sets front to 3 and writes 2 to items[3].
Show the answer
The answer is B. The first push sets front to (0 - 1 + 5) % 5 = 4 and writes 1 there. The second sets front to 3 and writes 2 to items[3].
If you only use pushBack and popBack on a deque, what structure do you get?
The answer is B. When adding and removing happen at the same end, the last element in is the first out. That is the LIFO rule of a stack.
Show the answer
The answer is B. When adding and removing happen at the same end, the last element in is the first out. That is the LIFO rule of a stack.
Lessons you mark show up in the curriculum. If you are signed in, they are saved to your account too.