In a music app, the "Play next" button puts a song at the front of the queue. The "Add to queue" button puts a song at the back. A song you no longer want can be removed from the back. A stack works at one end only. A queue adds at the back and takes from the front, so no song can join at the front. This list of songs needs both ends at the same time.
The data structure for this list of songs is called a deque (say "deck", short for Double-Ended Queue). A deque is a two-ended queue: you can add and take items at the front and at the back. Picture a line of people with a door at the front and a door at the back. People can join or leave through either door, but nobody can squeeze into the middle. The people are the items in the deque, and the two doors are its two ends.
Four operations at two ends
A deque has four operations: addFront and removeFront at the front, addBack and removeBack at the back. A plain array already has a method for each of the four. The array dq starts as ["B", "C"], and index 0 is the front:
| Step | Operation | Array code | Result | Contents (front to back) |
|---|---|---|---|---|
| 1 | addFront | dq.unshift("A") |
A joins at the front | A, B, C |
| 2 | addBack | dq.push("D") |
D joins at the back | A, B, C, D |
| 3 | removeFront | dq.shift() |
"A" |
B, C, D |
| 4 | removeBack | dq.pop() |
"D" |
B, C |
This is the code:
const dq = ["B", "C"]; // front to back
dq.unshift("A"); // addFront: ["A", "B", "C"]
dq.push("D"); // addBack: ["A", "B", "C", "D"]
console.log(dq.shift()); // removeFront: A
console.log(dq.pop()); // removeBack: D
console.log(dq); // ["B", "C"]
If you add and take at the same end (addBack with removeBack), the last one in is the first one out: the deque behaves like a stack. If you add at the back and take from the front (addBack with removeFront), the deque behaves like a queue. A deque is for when you need both ends at the same time. One example is checking a palindrome, a word that reads the same from the front or from the back, like "level". To check it, take one letter from the front and one from the back, compare them, then repeat.
Every operation O(1) with head and tail
The problem: unshift and shift move every item in the array, so both are O(n). The fix is the same as in the queue lesson: keep the items in an object with numbers as keys, like a row of numbered boxes. Then use two markers: head is the number of the front item, and tail the number just after the back item (where a new item joins at the back).
The difference from a queue: items can also join a deque at the front. That's why head may go below zero. This table records five operations, starting from an empty deque:
| Step | Code | head |
tail |
Contents (number: item) |
|---|---|---|---|---|
| 1 | addBack("B") |
0 | 1 | 0: B |
| 2 | addBack("C") |
0 | 2 | 0: B, 1: C |
| 3 | addFront("A") |
-1 | 2 | -1: A, 0: B, 1: C |
| 4 | removeFront() gives "A" |
0 | 2 | 0: B, 1: C |
| 5 | removeBack() gives "C" |
0 | 1 | 0: B |
This is a Deque class that works that way. A class is a template for making objects. new Deque() makes one deque and runs constructor once, which sets up an empty items and puts head and tail at 0. this means the deque itself.
class Deque {
constructor() {
this.items = {};
this.head = 0; // number of the front item
this.tail = 0; // number just after the back item
}
addFront(item) {
this.head--;
this.items[this.head] = item;
}
addBack(item) {
this.items[this.tail] = item;
this.tail++;
}
removeFront() {
if (this.head === this.tail) return undefined; // empty
const item = this.items[this.head];
delete this.items[this.head];
this.head++;
return item;
}
removeBack() {
if (this.head === this.tail) return undefined; // empty
this.tail--;
const item = this.items[this.tail];
delete this.items[this.tail];
return item;
}
}
addFrontmovesheadback first (subtracts one from it), then fills the box numberedhead.addBackfills the box numberedtailfirst, then movestailforward.removeFrontworks like dequeue in a queue: take the item in the box numberedhead, delete that box, then moveheadforward.
removeBack runs in three steps:
- If the deque is empty (
headequalstail), returnundefined. Both remove methods check this, so the markers don't move. - Move
tailback one, sotailpoints at the back item. - Read the item in that box into the variable
item, remove the box withdelete, then returnitem.
The number of items is tail - head, so a size() method just returns that number.
All four operations are now O(1): each operation changes only one box and one marker, and no item has to move.
⚠️ A negative head, a tail one place too far, and an empty deque
- Being surprised by a negative
head. AfteraddFront, keys can be -1, -2 and so on. An object can have negative keys, so it's normal. - The order inside removeBack.
tailpoints one place after the last item, and the box at that number is empty. If you read the item before loweringtail, you getundefined. - Taking from an empty deque without a check.
taildrops belowhead, and the number of items goes negative. Check for empty at the start of both remove methods. - A deque when one end is enough. If you only need one end, a stack or a queue is simpler and says what you mean more clearly.
TL;DR: A deque (Double-Ended Queue) is a two-ended queue: you can add and take items at the front and at the back, with four operations, addFront, addBack, removeFront and removeBack. If you add and take at the same end, the deque behaves like a stack. If you add at the back and take from the front, it behaves like a queue. With an array, push and pop at the back are O(1), but unshift and shift at the front are O(n), because every other item has to move. All four can be O(1) if you keep the items in an object with numbers as keys, plus two markers: head (the number of the front item) and tail (the number just after the back item). head may go negative, because addFront subtracts from it. The number of items is tail - head, and the remove methods return undefined when the deque is empty.
⚡ Two ends, four operations
Write:
const dq = ["B", "C"]; // front to back
dq.unshift("A"); // addFront: ["A", "B", "C"]
dq.push("D"); // addBack: ["A", "B", "C", "D"]
console.log(dq.shift()); // removeFront: A
console.log(dq.pop()); // removeBack: D
Meaning: A deque (Double-Ended Queue) is a two-ended queue: you can add and take items at the front and at the back, but no item can squeeze into the middle. In the array dq, index 0 is the front, and the comment on each line names the operation.
⚡ A stack or a queue
Guess first: you use addBack, then removeBack. Does the deque behave like a stack or like a queue?
Like a stack. You add and take at the same end, so the last one in is the first one out. If you use addBack with removeFront, the deque behaves like a queue.
Meaning: A deque is for when you need both ends at the same time. One example is checking a palindrome, a word that reads the same from the front or from the back, like "level". Take one letter from the front and one from the back, compare them, then repeat.
⚡ head may go negative
Write:
addFront(item) {
this.head--;
this.items[this.head] = item;
}
Meaning: With an array, unshift and shift are O(n), because every other item has to move. The Deque class (a template for making deques) is faster: it keeps its items in the object this.items with numbers as keys, and this means the deque itself. The marker head is the number of the front item, and tail the number just after the back item. This addFront method moves head back first, then stores the item at that number. So keys can be -1, -2, and that's normal. All four operations become O(1), and the number of items is tail - head.