Conceptcore
Deque
Also called double-ended queue, dequeue at both ends, ArrayDeque, VecDeque, collections.deque, std::deque, deck.
A deque, or double-ended queue, adds and removes items at both ends. It can serve as a stack and as a queue, and most libraries build it on a ring buffer or on linked blocks.
- Applies to
- core-languages
Idea
A deque is a queue that is open at both ends. Wikipedia describes it as "a generalization of both the stack and the queue".1 A program can add an item at the front or at the back, and remove an item from the front or from the back. Used at one end only, a deque is a stack. Added at one end and removed at the other, it is a queue.
The name is short for "double ended queue", and it "is usually pronounced" like the word deck.2
from collections import deque
def is_palindrome(text: str) -> bool:
letters = deque(ch.lower() for ch in text if ch.isalnum())
while len(letters) > 1:
if letters.popleft() != letters.pop():
return False
return True
for text in ["Never odd or even", "deque", "A man, a plan, a canal: Panama"]:
print(text, "yes" if is_palindrome(text) else "no")
Never odd or even yes
deque no
A man, a plan, a canal: Panama yes
How it works
Operations. A deque has an add, a remove and a peek operation at each end. Java's Deque is "A linear collection that supports element insertion and removal at both ends."2 Its methods come in pairs, such as addFirst and addLast, pollFirst and pollLast.
Implementations. Wikipedia names "at least two common ways to efficiently implement a deque": "with a doubly linked list or with a modified dynamic array".1
- A ring buffer keeps the items in one array with a front index. Both indexes wrap around, and the array grows when it is full. Java's
ArrayDequeand Rust'sVecDequework this way.VecDequeis "A double-ended queue implemented with a growable ring buffer."3 - A list of fixed-size blocks adds a new block when one end is full. C++
std::dequeuses "a sequence of individually allocated fixed-size arrays".4 Python's deque is built in a similar way, as "a doubly linked list of fixed-length subarrays".1 - A doubly linked list has a constant cost at both ends, but each item is a separate node. Go's
container/listis one.5
Index access. Some deques also give access by index. Python: "Indexed access is O(1) at both ends but slows to O(n) in the middle."6 std::deque "is an indexed sequence container that allows fast insertion and deletion at both its beginning and its end".4 Java's ArrayDeque has no index access, "contrary to its name".1
In languages
| Language | Verdict | Note |
|---|---|---|
| Python | Standard library | |
| C++ | Standard library | |
| Java | Standard library | |
| C | Idiom | |
| C# | Standard library | |
| JavaScript | Idiom | |
| TypeScript | Idiom | TypeScript uses a JavaScript array as a deque, with push, pop, shift and unshift. No example file exists. |
| Go | Standard library | |
| Rust | Standard library | |
| Kotlin | Standard library | Kotlin has ArrayDeque, a resizable array deque with addFirst, addLast, removeFirst and removeLast. No example file exists because kotlinc is not installed. |
| SQL | Does not apply | A table is a set of rows with no ends. An order column can emulate a deque, but SQL has no deque type. |
| Bash | Idiom | An indexed array works as a deque, with assignments at both ends and unset to remove an element. No example file exists. |
| PowerShell | Standard library | [System.Collections.Generic.LinkedList[T]] from .NET adds and removes at both ends. No example file exists because pwsh is not installed. |
| HTML | Does not apply | HTML is markup. It has no data structures for a program. |
| CSS | Does not apply | CSS style rules have no data structures. |
| Regular expressions | Does not apply | A regular expression matches text. It has no data structures. |
| Language | Verdict | Form |
|---|---|---|
| Python | stdlib | collections.deque, with an optional maxlen6 |
| JavaScript | idiom | an array with push, pop, shift and unshift1 |
| TypeScript | idiom | an array, as in JavaScript |
| Java | stdlib | the Deque interface, with ArrayDeque and LinkedList27 |
| C | idiom | a ring buffer in an array, or a doubly linked list |
| C++ | stdlib | std::deque4 |
| C# | stdlib | LinkedList<T>; no array-based deque type |
| Go | stdlib | container/list, a doubly linked list5 |
| Rust | stdlib | VecDeque3 |
| Kotlin | stdlib | ArrayDeque |
| PowerShell | stdlib | [System.Collections.Generic.LinkedList[T]] from .NET |
| Bash | idiom | an indexed array |
| SQL | n/a | a table has no ends; an order column can emulate them |
| Regex | n/a | a pattern has no data structures |
| HTML/CSS | n/a | markup and style rules have no data structures |
Python. The documentation says that "Deques are a generalization of stacks and queues".6 They "support thread-safe, memory efficient appends and pops from either side of the deque with approximately the same O(1) performance in either direction".6 A deque with a maxlen drops items from the other end when it is full: "Bounded length deques provide functionality similar to the tail filter in Unix."6
Java. The Deque documentation says: "Deques can also be used as LIFO (Last-In-First-Out) stacks. This interface should be used in preference to the legacy Stack class."2 ArrayDeque "is likely to be faster than Stack when used as a stack, and faster than LinkedList when used as a queue".7 It does not accept null: "Null elements are prohibited."7
C++. "As opposed to std::vector, the elements of a deque are not stored contiguously".4 An insert or a removal at either end "never invalidates pointers or references to the rest of the elements".4
Rust. The collections guide says to use a VecDeque when "You want a Vec that supports efficient insertion at both ends of the sequence."8 Because the items are in a ring buffer, they can be in two parts of the array. as_slices "Returns a pair of slices which contain, in order, the contents of the deque", and make_contiguous moves the items into one part.3
JavaScript and Go. JavaScript arrays have push, pop, shift and unshift, so an array can act as a deque.1 shift and unshift move the other items, so they are slow for a large array. Go's container/list "implements a doubly linked list" with PushFront, PushBack, Remove, Front and Back.5
The example files add items at both ends, remove items from both ends, and show one extra feature of each library type.
from collections import deque
d = deque(["b", "c"])
d.appendleft("a")
d.append("d")
print(list(d), "front", d[0], "back", d[-1])
print(d.popleft(), d.pop(), list(d))
d.extend(["x", "y", "z"])
d.rotate(1)
print("rotate 1:", list(d))
last_three = deque(range(10), maxlen=3)
print("maxlen 3:", list(last_three))
['a', 'b', 'c', 'd'] front a back d
a d ['b', 'c']
rotate 1: ['z', 'b', 'c', 'x', 'y']
maxlen 3: [7, 8, 9]
- Verdict: stdlib.
collections.dequehasappendandpopat the right end, andappendleftandpopleftat the left end. rotate(1)moves the last item to the front.- With
maxlen, the deque keeps only the newest items.
#include <deque>
#include <iostream>
void print(const std::deque<int>& d) {
for (std::size_t i = 0; i < d.size(); i++) {
std::cout << (i == 0 ? "" : " ") << d[i];
}
std::cout << '\n';
}
int main() {
std::deque<int> d = {2, 3};
d.push_front(1);
d.push_back(4);
print(d);
std::cout << "front " << d.front() << " back " << d.back() << " d[2] " << d[2] << '\n';
// A reference to an item stays valid after inserts at the ends.
const int& second = d[1];
for (int i = 0; i < 1000; i++) {
d.push_front(-i);
d.push_back(i);
}
std::cout << "second item still " << second << ", size " << d.size() << '\n';
d.pop_front();
d.pop_back();
std::cout << "front " << d.front() << " back " << d.back() << '\n';
}
1 2 3 4
front 1 back 4 d[2] 3
second item still 2, size 2004
front -998 back 998
- Verdict: stdlib.
std::dequehaspush_front,push_back,pop_front,pop_backand index access with[]. - An insert at either end keeps references to the other items valid. A
std::vectordoes not give this guarantee.
import java.util.ArrayDeque;
import java.util.Deque;
public class Main {
public static void main(String[] args) {
Deque<String> d = new ArrayDeque<>();
d.addLast("b");
d.addLast("c");
d.addFirst("a");
d.addLast("d");
System.out.println(d + " front " + d.peekFirst() + " back " + d.peekLast());
System.out.println(d.pollFirst() + " " + d.pollLast() + " " + d);
// The same deque as a stack and as a queue.
d.push("top");
d.offer("tail");
System.out.println(d + " pop " + d.pop() + " poll " + d.poll());
System.out.println("descending: " + String.join(",", (Iterable<String>) d::descendingIterator));
}
}
[a, b, c, d] front a back d
a d [b, c]
[top, b, c, tail] pop top poll b
descending: tail,c
- Verdict: stdlib.
ArrayDequeimplementsDeque, withaddFirst,addLast,pollFirst,pollLast,peekFirstandpeekLast. pushandpopwork at the front, andofferandpolluse the deque as a queue.descendingIteratorwalks from the back to the front.
#include <stdbool.h>
#include <stdio.h>
#define CAPACITY 4
/* A ring buffer with a front index. Both ends wrap around. */
struct deque {
int items[CAPACITY];
int front;
int count;
};
static bool push_front(struct deque *d, int v) {
if (d->count == CAPACITY) {
return false;
}
d->front = (d->front + CAPACITY - 1) % CAPACITY;
d->items[d->front] = v;
d->count++;
return true;
}
static bool push_back(struct deque *d, int v) {
if (d->count == CAPACITY) {
return false;
}
d->items[(d->front + d->count) % CAPACITY] = v;
d->count++;
return true;
}
static bool pop_front(struct deque *d, int *out) {
if (d->count == 0) {
return false;
}
*out = d->items[d->front];
d->front = (d->front + 1) % CAPACITY;
d->count--;
return true;
}
static bool pop_back(struct deque *d, int *out) {
if (d->count == 0) {
return false;
}
d->count--;
*out = d->items[(d->front + d->count) % CAPACITY];
return true;
}
static void print(const struct deque *d) {
printf("[");
for (int i = 0; i < d->count; i++) {
printf(i == 0 ? "%d" : " %d", d->items[(d->front + i) % CAPACITY]);
}
printf("] front index %d\n", d->front);
}
int main(void) {
struct deque d = {.front = 0, .count = 0};
push_back(&d, 2);
push_back(&d, 3);
push_front(&d, 1);
print(&d);
printf("push_back 4: %s\n", push_back(&d, 4) ? "yes" : "no");
printf("push_back 5: %s\n", push_back(&d, 5) ? "yes" : "no");
int a = 0;
int b = 0;
pop_front(&d, &a);
pop_back(&d, &b);
printf("popped %d and %d\n", a, b);
print(&d);
return 0;
}
[1 2 3] front index 3
push_back 4: yes
push_back 5: no
popped 1 and 4
[2 3] front index 0
- Verdict: idiom. C has no deque type. A fixed array with a front index and a count is a bounded deque.
push_frontmoves the front index back by one, so it wraps from 0 to the last slot of the array.
var d = new LinkedList<string>(new[] { "b", "c" });
d.AddFirst("a");
d.AddLast("d");
Console.WriteLine($"{string.Join(",", d)} front {d.First!.Value} back {d.Last!.Value}");
var front = d.First!.Value;
d.RemoveFirst();
var back = d.Last!.Value;
d.RemoveLast();
Console.WriteLine($"{front} {back} {string.Join(",", d)}");
try
{
d.Clear();
d.RemoveFirst();
}
catch (InvalidOperationException)
{
Console.WriteLine("RemoveFirst on empty: InvalidOperationException");
}
a,b,c,d front a back d
a d b,c
RemoveFirst on empty: InvalidOperationException
- Verdict: stdlib. .NET has no array-based deque type.
LinkedList<T>adds and removes at both ends withAddFirst,AddLast,RemoveFirstandRemoveLast. FirstandLastarenullon an empty list, andRemoveFirstthrowsInvalidOperationException.
const d = ["b", "c"];
d.unshift("a");
d.push("d");
console.log(d.join(","), "front", d[0], "back", d.at(-1));
console.log(d.shift(), d.pop(), d.join(","));
// Both ends of an empty array give undefined.
const empty = [];
console.log(empty.shift(), empty.pop());
a,b,c,d front a back d
a d b,c
undefined undefined
- Verdict: idiom. An array works as a deque:
pushandpopat the back,unshiftandshiftat the front. shiftandunshiftmove every other item, so a large deque needs a ring buffer.
package main
import (
"container/list"
"fmt"
)
func values(l *list.List) []any {
var out []any
for e := l.Front(); e != nil; e = e.Next() {
out = append(out, e.Value)
}
return out
}
func main() {
d := list.New()
d.PushBack("b")
d.PushBack("c")
d.PushFront("a")
d.PushBack("d")
fmt.Println(values(d), "front", d.Front().Value, "back", d.Back().Value)
front := d.Remove(d.Front())
back := d.Remove(d.Back())
fmt.Println(front, back, values(d))
// Front and Back return nil on an empty list.
d.Init()
fmt.Println("front of empty:", d.Front())
}
[a b c d] front a back d
a d [b c]
front of empty: <nil>
- Verdict: stdlib.
container/listis a doubly linked list, and it works as a deque withPushFront,PushBack,Front,BackandRemove. - The values have the type
any, so a program needs a type assertion to use them.
use std::collections::VecDeque;
fn main() {
let mut d: VecDeque<i32> = VecDeque::from([2, 3]);
d.push_front(1);
d.push_back(4);
println!("{d:?} front {:?} back {:?} d[2] {}", d.front(), d.back(), d[2]);
let first = d.pop_front();
let last = d.pop_back();
println!("{first:?} {last:?} {d:?}");
// After push_front, the items can sit in two parts of the ring buffer.
let mut ring: VecDeque<i32> = VecDeque::with_capacity(4);
ring.push_back(2);
ring.push_back(3);
ring.push_front(1);
let (a, b) = ring.as_slices();
println!("total {} items", a.len() + b.len());
ring.make_contiguous();
println!("contiguous {:?}", ring.as_slices().0);
d.rotate_left(1);
println!("rotate_left 1: {d:?}");
}
[1, 2, 3, 4] front Some(1) back Some(4) d[2] 3
Some(1) Some(4) [2, 3]
total 3 items
contiguous [1, 2, 3]
rotate_left 1: [3, 2]
- Verdict: stdlib.
VecDequeis a growable ring buffer withpush_front,push_back,pop_front,pop_backand index access. - The items can be in two parts of the buffer.
as_slicesreturns both parts, andmake_contiguousjoins them.
Variations and related ideas
- Bounded deque. A deque with a maximum size. Python's
maxlendrops the oldest item at the other end. See Ring buffer. - Input-restricted and output-restricted deques. One end only adds, or one end only removes.1
- Work stealing. Each processor keeps a deque of tasks. It takes tasks from its own end, and another processor with no work takes tasks from the other end.1
- Monotonic queue. A deque that keeps its items in increasing or decreasing order. It finds the minimum or maximum of a sliding window in linear time.1
- Stack and queue. The two restricted forms of a deque. See stack-data-structure and queue-concept.
Pitfalls
Java's ArrayDeque rejects null
ArrayDeque prohibits null items, and an add of null throws NullPointerException.7 LinkedList accepts them. Code that moves from LinkedList to ArrayDeque can fail at run time.
This code runs but gives a wrong answer on purpose.
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.LinkedList;
public class Main {
public static void main(String[] args) {
Deque<String> linked = new LinkedList<>();
linked.addLast(null);
System.out.println("LinkedList size " + linked.size());
Deque<String> array = new ArrayDeque<>();
try {
array.addLast(null);
} catch (NullPointerException e) {
System.out.println("ArrayDeque: NullPointerException");
}
}
}
LinkedList size 1
ArrayDeque: NullPointerException
Use a marker object or an Optional in place of null.
Index access in the middle of a deque is slow
A Python deque reads items near its ends in constant time, but d[i] in the middle walks the blocks: "Indexed access is O(1) at both ends but slows to O(n) in the middle. For fast random access, use lists instead."6 A loop such as for i in range(len(d)): d[i] is then quadratic. Iterate over the deque directly, or copy it to a list first.
A bounded deque drops items without an error
A Python deque with maxlen never raises an error when it is full. It discards an item from the other end.6
This code runs but gives a wrong answer on purpose.
from collections import deque
recent = deque(maxlen=3)
for n in range(1, 6):
recent.append(n)
print(list(recent), "length", len(recent))
recent.appendleft(0)
print(list(recent))
[3, 4, 5] length 3
[0, 3, 4]
This is right for a log of recent events. It is wrong for a work queue, where each item must be done.
Cost
| Operation | Ring buffer (ArrayDeque, VecDeque) |
Blocks (std::deque, Python deque) |
Doubly linked list |
|---|---|---|---|
| add or remove at either end | amortized constant | constant | constant, with one allocation |
| peek at either end | constant | constant | constant |
| item at index i | constant, or none in Java | constant in C++; linear in the middle in Python | linear |
| insert in the middle | linear | linear | constant at a known node |
VecDeque::rotate_left(n) takes time in proportion to the smaller of n and len() - n, "and no extra space".3
History
Wikipedia reports that a CTSS technical note of 1965 had subroutines that placed a user at the end or at the beginning of a queue, "before even the deque is named".1 Donald Knuth treated stacks, queues and deques together in The Art of Computer Programming, volume 1, section 2.2.1, "Stacks, Queues, and Deques".1 "As of Java 6, Java's Collections Framework provides a new Deque interface", and "Python 2.4 introduced the collections module with support for deque objects".1
References
- Double-ended queue, Wikipedia, the introduction; Implementations; Language support; Applications
- Deque (Java SE 27 and JDK 27), the interface description
- Struct VecDeque, The Rust Standard Library, the description; rotate_left
- std::deque, cppreference.com, the introduction
- list package, container/list, Go standard library, Overview; type List
- collections, Container datatypes, Python documentation, deque objects
- ArrayDeque (Java SE 27 and JDK 27), the class description
- Module std::collections, The Rust Standard Library, When Should You Use Which Collection?
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Visual | V0 none |
|
| Writing | W4 complete |
|
Tag QYEZ3S Edit this page History Report an error Markdown