AlgoTales · Roadmap

Deque

Intermediate · 8 min · code in PHP, JavaScript, Java and Go

Where you will meet this in real life

A deque (double-ended queue, said "deck") lets you add and remove at both the front and the back. It combines the abilities of a stack and a queue, so one structure can serve many tasks that need both ends.

Practical use cases

  • Web app: Recent items list with both-end control. A browser-style history keeps the last 50 pages: new pages go in at the front, and the oldest at the back are dropped when it is full. A deque handles both operations in one step each, with no shifting of the other 49 items.
  • Web app: Undo history with a size limit. An editor adds each new edit at one end, and undo takes the latest edit from that same end. When the history limit is reached, the oldest edit is quietly dropped from the other end. A deque supports all three actions quickly in one structure.
  • System: Work stealing and sliding windows. Thread pools let idle workers steal tasks from the back of a busy worker's list while the owner works from the front. Sliding-window problems also use a deque to drop stale items from one end and add new ones at the other.

The story: The Two-Door Bus

The Number 21 bus in Pune had a strange rule that confused everyone: passengers could board from the front door or the back door, and could get off from either door too. Conductor Meena called it "the two-door system".

Why? Elderly passengers boarded at the front near the reserved seats, while a college crowd rushed in at the back. Someone who had to leave early squeezed out through whichever door was closer. If the bus had only one door, the whole line would shuffle and fight.

Meena's nephew Kabir was learning about queues at school. "A normal queue is a one-way street: in at the back, out at the front. Your bus is a deque, a double-ended queue. Add and remove at both ends and it still keeps its order in the middle!" The best part: a deque can pretend to be a queue or a stack, whichever the job needs.

How to spot this problem, and where you need it

You need to add or remove items at both ends of a list, quickly, and using an array with shift and unshift makes the page slower as the list grows.

Signs you need it

  • The feature needs both "add newest in front, drop oldest at back" behaviour, such as a recent list with a maximum size.
  • Your code uses array_unshift and array_pop on the same large array and the cost rises with size.
  • The problem mentions "double-ended", "both ends" or a window that moves along a series.

Where to use it in a project

  • Recent history lists, such as recently viewed or visited items with a fixed maximum.
  • Undo and redo stacks that also need to drop the oldest entries.
  • Sliding-window computations over streams of prices or readings.

The solution

Use a structure that tracks both ends, such as a two-way linked chain or a circular array. Push front and push back add at either end, pop front and pop back remove from either end, each in a single step. Because no other items move, the cost does not depend on how long the list is.

Payoff: Before: shifting 10,000 items in an array for each insert at the front. After: one step per operation at either end.

Explain it like I am 8

A queue is a slide: you climb on at the top and slide out at the bottom. A deque is a tunnel with an opening at both ends: you can walk in or out of either side.

How it works, step by step

  1. Keep the items in a line with a front and a back.
  2. pushBack(x) and popBack() work at the back, like a stack's top.
  3. pushFront(x) and popFront() work at the front, like a queue's exit.
  4. To keep every operation instant, the front index is allowed to go below the starting index (it can be negative in our code), so nothing has to be shifted.
  5. Use only the back door for entry and the front door for exit and you have a normal queue. Use only the back door for both and you have a stack.

The code in four languages

PHP

<?php
// A deque where every operation is O(1): items live in an array whose
// keys run from $front up to $back, and $front can go negative.
class Deque {
    private array $items = [];
    private int $front = 0;   // key of the first item
    private int $back = -1;   // key of the last item (empty when back < front)

    public function pushBack($x): void  { $this->items[++$this->back] = $x; }
    public function pushFront($x): void { $this->items[--$this->front] = $x; }
    public function popBack() {
        if ($this->isEmpty()) return null;
        $x = $this->items[$this->back];
        unset($this->items[$this->back--]);
        return $x;
    }
    public function popFront() {
        if ($this->isEmpty()) return null;
        $x = $this->items[$this->front];
        unset($this->items[$this->front++]);
        return $x;
    }
    public function isEmpty(): bool { return $this->back < $this->front; }
    public function toArray(): array {
        $out = [];
        for ($i = $this->front; $i <= $this->back; $i++) $out[] = $this->items[$i];
        return $out;
    }
}

$d = new Deque();
$d->pushBack(5); $d->pushBack(7);     // 5 7
$d->pushFront(3); $d->pushFront(1);   // 1 3 5 7
echo implode(' ', $d->toArray()) . "\n";
echo "popBack: " . $d->popBack() . "\n";     // 7
echo "popFront: " . $d->popFront() . "\n";   // 1
echo implode(' ', $d->toArray()) . "\n";     // 3 5

JavaScript

// A deque where every operation is O(1): items live in an object whose
// keys run from front up to back, and front can go negative.
class Deque {
  constructor() {
    this.items = {};
    this.front = 0;    // key of the first item
    this.back = -1;    // key of the last item (empty when back < front)
  }
  pushBack(x)  { this.items[++this.back] = x; }
  pushFront(x) { this.items[--this.front] = x; }
  popBack() {
    if (this.isEmpty()) return null;
    const x = this.items[this.back];
    delete this.items[this.back--];
    return x;
  }
  popFront() {
    if (this.isEmpty()) return null;
    const x = this.items[this.front];
    delete this.items[this.front++];
    return x;
  }
  isEmpty() { return this.back < this.front; }
  toArray() {
    const out = [];
    for (let i = this.front; i <= this.back; i++) out.push(this.items[i]);
    return out;
  }
}

const d = new Deque();
d.pushBack(5); d.pushBack(7);     // 5 7
d.pushFront(3); d.pushFront(1);   // 1 3 5 7
console.log(d.toArray().join(' '));
console.log('popBack: ' + d.popBack());     // 7
console.log('popFront: ' + d.popFront());   // 1
console.log(d.toArray().join(' '));         // 3 5

Java

import java.util.*;

public class Main {
    // A deque where every operation is O(1): items live in a map whose
    // keys run from front up to back, and front can go negative.
    static class Deque {
        private final Map<Integer, Integer> items = new HashMap<>();
        private int front = 0;    // key of the first item
        private int back = -1;    // key of the last item (empty when back < front)

        void pushBack(int x)  { items.put(++back, x); }
        void pushFront(int x) { items.put(--front, x); }

        Integer popBack() {
            if (isEmpty()) return null;
            return items.remove(back--);
        }

        Integer popFront() {
            if (isEmpty()) return null;
            return items.remove(front++);
        }

        boolean isEmpty() { return back < front; }

        List<Integer> toList() {
            List<Integer> out = new ArrayList<>();
            for (int i = front; i <= back; i++) out.add(items.get(i));
            return out;
        }
    }

    public static void main(String[] args) {
        Deque d = new Deque();
        d.pushBack(5); d.pushBack(7);     // 5 7
        d.pushFront(3); d.pushFront(1);   // 1 3 5 7
        System.out.println(d.toList());   // [1, 3, 5, 7]
        System.out.println("popBack: " + d.popBack());     // 7
        System.out.println("popFront: " + d.popFront());   // 1
        System.out.println(d.toList());   // [3, 5]
    }
}

Go

package main

import "fmt"

// Deque is a deque where every operation is O(1): items live in a map whose
// keys run from front up to back, and front can go negative.
type Deque struct {
	items map[int]int
	front int // key of the first item
	back  int // key of the last item (empty when back < front)
}

func NewDeque() *Deque { return &Deque{items: map[int]int{}, back: -1} }

func (d *Deque) PushBack(x int) {
	d.back++
	d.items[d.back] = x
}

func (d *Deque) PushFront(x int) {
	d.front--
	d.items[d.front] = x
}

func (d *Deque) PopBack() (int, bool) {
	if d.IsEmpty() {
		return 0, false
	}
	x := d.items[d.back]
	delete(d.items, d.back)
	d.back--
	return x, true
}

func (d *Deque) PopFront() (int, bool) {
	if d.IsEmpty() {
		return 0, false
	}
	x := d.items[d.front]
	delete(d.items, d.front)
	d.front++
	return x, true
}

func (d *Deque) IsEmpty() bool { return d.back < d.front }

func (d *Deque) ToSlice() []int {
	var out []int
	for i := d.front; i <= d.back; i++ {
		out = append(out, d.items[i])
	}
	return out
}

func main() {
	d := NewDeque()
	d.PushBack(5)
	d.PushBack(7) // 5 7
	d.PushFront(3)
	d.PushFront(1)           // 1 3 5 7
	fmt.Println(d.ToSlice()) // [1 3 5 7]
	last, _ := d.PopBack()
	fmt.Println("popBack:", last) // 7
	first, _ := d.PopFront()
	fmt.Println("popFront:", first) // 1
	fmt.Println(d.ToSlice())        // [3 5]
}

Time: O(1) · Extra space: O(n). Each push or pop touches only one end; space is just the n items stored.

Watch out for

  • Using array_unshift or shift/unshift on a plain array for the front: they move every item and cost O(n).
  • Forgetting to check for empty before popping from either end.
  • Thinking a deque is "a queue with extras" and mixing the two ends carelessly, so the order of service is no longer what you intended.

Quick check

  1. Which ends of a deque can you add to?
    • Only the back
    • Only the front
    • Both the front and the back
  2. If you only push at the back and pop at the front, a deque behaves like a...
    • Stack
    • Queue
    • Sorted list
  3. If you push and pop only at the back, a deque behaves like a...
    • Queue
    • Priority queue
    • Stack