Lesson 17 · Linear structures

Deques

A deque, pronounced "deck", is a list you can add to and remove from at both ends in O(1). Use only one end and it is a stack; add at one end and remove at the other and it is a queue.

Deques concept diagramA visual explanation of the layout and operations shown in this lesson.insert and remove at either end in constant timeracefrontbacka double-ended queue is both a stack and a queue
1

What a Deque Is

A deque (short for double ended queue, said "deck") is a sequence that allows adding and removing at both ends. A stack works at one end only. A queue adds at the back and removes at the front. The deque data structure drops both limits and lets each call choose its end.

So a deque can stand in for either. Use only push_back and pop_back and it is a stack. Use only push_back and pop_front and it is a queue.

  • Both ends open for adding and removing
  • Middle positions are not changed by the core operations
2

Deque Operations

The core deque operations each touch one end and cost O(1). Most libraries add peeks at both ends and a size check, and names differ by language.

The same operations in three languages
OperationPython collections.dequeC++ std::dequeJava ArrayDeque
Add at backappend(x)push_back(x)addLast(x)
Add at frontappendleft(x)push_front(x)addFirst(x)
Remove from backpop()pop_back()removeLast()
Remove from frontpopleft()pop_front()removeFirst()
Look at either endd[-1], d[0]back(), front()peekLast(), peekFirst()
  • Removing from an empty deque is an error: IndexError in Python, an exception in Java, undefined behaviour in C++
  • Python's deque also takes maxlen, which drops items from the far end when full
3

Deque Implementation

Circular array. Keep a block of slots, the index of the front item and a count. push_back writes to (front + size) mod capacity; push_front moves front to (front − 1) mod capacity, wrapping to the far end of the block. Nothing ever shifts. When the block is full, copy everything into one twice as large, which keeps pushes O(1) on average. Java's ArrayDeque works this way. It uses the same wrap-around as a circular queue, with the front allowed to move both ways.

List of blocks. C++'s std::deque keeps fixed-size blocks plus a small table of pointers to them. Growing at either end adds a block, so existing items never move and references to them stay valid. Finding item k is arithmetic on the block size, so indexing is O(1). Python's collections.deque is a doubly linked list of 64-item blocks: fast at both ends, but indexing the middle walks block by block, O(n).

Doubly linked list. Head and tail pointers plus prev and next in every node give strictly O(1) at both ends with no copying ever. It costs two pointers per item and scattered memory, so walking it is slower than an array. See doubly linked lists.

A plain array, like a Python list, is not a good deque: it starts at slot 0, so adding or removing at the front shifts every item, O(n). That is why list.pop(0) is slow and deque.popleft() is not.

Three ways to store a deque
Circular arrayList of blocksDoubly linked list
Push or pop at an endO(1) on averageO(1)O(1)
Read item kO(1)O(1) in C++, O(n) in PythonO(n)
Items move when it growsyes, copied oncenono
Used byJava ArrayDequeC++ std::deque, Python dequehand-written lists
  • Circular array: one block, wrap-around indexes, doubles when full
  • Blocks: no item ever moves, so references stay valid
Key reference

Terms, operations, and practical uses

Operations

  • push_front / push_backAdd an item at the front or the back. O(1) in every standard implementation.
  • pop_front / pop_backRemove and return the item at one end. Calling either on an empty deque is an error.
  • front / backLook at an end without removing it.

Storage

  • Circular arrayOne block of slots, a front index and a size; indexes wrap round with mod. Doubles when full.
  • Block listFixed-size blocks plus a table of pointers to them. Items never move when the deque grows.
  • Doubly linked listNodes with prev and next pointers, plus head and tail. Strict O(1) at the ends, O(n) to reach the middle.

Uses

  • Palindrome checkCompare and pop both ends until at most one item is left.
  • Sliding windowIndexes enter at the back and leave from the front as the window moves.
  • Work stealingOwner works at the back of its deque; other threads take from the front.
Implementation

Code in Python, C++ and Java

from collections import deque


def is_palindrome(word):
    d = deque(word)
    while len(d) > 1:
        if d.popleft() != d.pop():
            return False
    return True


d = deque()
d.append(10)
d.append(20)
d.appendleft(5)
d.appendleft(1)
print("deque:", " ".join(map(str, d)))
print("pop_back:", d.pop())
print("pop_front:", d.popleft())
print("left:", " ".join(map(str, d)))
for word in ["racecar", "racecat"]:
    print(word + ":", "palindrome" if is_palindrome(word) else "not a palindrome")
#include <deque>
#include <iostream>
#include <string>
using namespace std;

bool isPalindrome(const string& word) {
    deque<char> d(word.begin(), word.end());
    while (d.size() > 1) {
        if (d.front() != d.back()) return false;
        d.pop_front();
        d.pop_back();
    }
    return true;
}

void show(const string& label, const deque<int>& d) {
    cout << label;
    for (int x : d) cout << " " << x;
    cout << "\n";
}

int main() {
    deque<int> d;
    d.push_back(10);
    d.push_back(20);
    d.push_front(5);
    d.push_front(1);
    show("deque:", d);
    cout << "pop_back: " << d.back() << "\n";
    d.pop_back();
    cout << "pop_front: " << d.front() << "\n";
    d.pop_front();
    show("left:", d);
    for (string word : {"racecar", "racecat"})
        cout << word << ": " << (isPalindrome(word) ? "palindrome" : "not a palindrome") << "\n";
}
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.StringJoiner;

public class Main {
    static boolean isPalindrome(String word) {
        Deque<Character> d = new ArrayDeque<>();
        for (char c : word.toCharArray()) d.addLast(c);
        while (d.size() > 1) {
            char first = d.removeFirst(), last = d.removeLast();
            if (first != last) return false;
        }
        return true;
    }

    static String show(Deque<Integer> d) {
        StringJoiner j = new StringJoiner(" ");
        for (int x : d) j.add(String.valueOf(x));
        return j.toString();
    }

    public static void main(String[] args) {
        Deque<Integer> d = new ArrayDeque<>();
        d.addLast(10);
        d.addLast(20);
        d.addFirst(5);
        d.addFirst(1);
        System.out.println("deque: " + show(d));
        System.out.println("pop_back: " + d.removeLast());
        System.out.println("pop_front: " + d.removeFirst());
        System.out.println("left: " + show(d));
        for (String word : new String[]{"racecar", "racecat"})
            System.out.println(word + ": " + (isPalindrome(word) ? "palindrome" : "not a palindrome"));
    }
}
Watch it run

Step through it

Running on push_back 10, 20; push_front 5, 1; pop_back; pop_front; then racecar and racecat

circular array: front index + sizedequeemptyslots01234567front = 0 · size = 0back = (front + size − 1) mod 8 · this is how Java's ArrayDeque workssize 0
Step 1

An empty deque in 8 slots

A deque (double-ended queue) lets you add and remove at both the front and the back. One common way to store it is a circular array: a fixed block of slots, the index of the front item, and a count. The back is not stored; it is (front + size − 1) mod 8. Nothing is in use yet.

Output
1 / 12
4

Deque vs Queue and Stack

A deque can do everything a queue or a stack can, so why not use it everywhere? Because a narrower type tells the reader something. A variable declared as a queue promises that nothing is removed from the back; with a deque, the reader has to check every call to know how it is used.

Speed matters less but points the same way. A deque tracks two ends, and block-based versions add a step on every access, so a plain dynamic array used as a stack is usually a little faster. Pick the deque when your code really uses both ends.

  • Queue: FIFO, one end in, the other out
  • Stack: LIFO, one end only
  • Deque: either end, both ways
5

Where Deques Are Used

Checking a palindrome: pop one character from each end and compare until one or none is left. See valid palindrome.

Sliding window maximum: keep indexes in a deque whose values decrease from front to back. New values push out smaller ones at the back, and indexes that leave the window come off the front. Each index goes in and out once, so the whole scan is O(n). The ordering rule is covered in monotonic queues; the problem is sliding window maximum.

Shortest paths with 0 and 1 weights: push a neighbour to the front if the edge costs 0 and to the back if it costs 1, as in 0-1 BFS.

Bounded history: undo lists and "last 100 events" logs add at one end and drop the oldest from the other. Work stealing: in thread pools, each worker takes tasks from the back of its own deque, while idle workers steal from the front of others'.

  • Both ends are used for different jobs in each case