Queue & deque
A queue adds at the back and removes from the front, first in, first out; a deque does both at either end. All in O(1).
Description
A queue processes items in the order they arrive: enqueue at the back, dequeue from the front. First in, first out: FIFO. It's the natural structure for anything that waits its turn: print jobs, network packets, requests, tasks for a worker, and the frontier of a breadth-first search.
A deque (double-ended queue, pronounced "deck") allows adding and removing at both ends. It can act as a stack, a queue, or both, and it's the right tool for sliding-window algorithms and work-stealing schedulers.
The implementation matters. Removing from the front of a plain array shifts every remaining item: O(n). Real queues use a ring buffer (an array with wrapping head and tail indexes) or a linked list, both O(1) at the ends.
How it works
A queue: dequeue at the front, enqueue at the back
- index 0: job1
- index 1: job2
- index 2: job3
- index 3: job4
As a linked list, with O(1) operations at both ends
- node 0: job1, next job2
- node 1: job2, next job3
- node 2: job3, next job4
- node 3: job4, next null
Complexity
| Operation | Average | Worst |
|---|---|---|
| Enqueue (add at the back)Amortized, if backed by a growing ring buffer. | O(1) | O(1) |
| Dequeue (remove from the front)O(n) with array.shift(). | O(1) | O(1) |
| Deque: add or remove at either end | O(1) | O(1) |
| Peek at the front or back | O(1) | O(1) |
Space: O(n)
In JavaScript, array.shift() is O(n) in general. For large queues, use a head index or a ring buffer, as in the example.
TypeScript implementation
A deque backed by a growable ring buffer: O(1) push and pop at both ends.
// A deque backed by a ring buffer that doubles when full. Indexes wrap around
// the end of the array, so both ends are O(1) without shifting anything.
export class Deque<T> {
private buf: (T | undefined)[];
private head = 0; // index of the first item
private count = 0;
constructor(capacity = 4) {
this.buf = new Array(capacity);
}
get size(): number {
return this.count;
}
private at(i: number): number {
return (this.head + i) % this.buf.length;
}
pushBack(v: T): void {
if (this.count === this.buf.length) this.grow();
this.buf[this.at(this.count)] = v;
this.count++;
}
pushFront(v: T): void {
if (this.count === this.buf.length) this.grow();
this.head = (this.head - 1 + this.buf.length) % this.buf.length;
this.buf[this.head] = v;
this.count++;
}
popFront(): T | undefined {
if (!this.count) return undefined;
const v = this.buf[this.head];
this.buf[this.head] = undefined;
this.head = (this.head + 1) % this.buf.length;
this.count--;
return v;
}
popBack(): T | undefined {
if (!this.count) return undefined;
const i = this.at(this.count - 1);
const v = this.buf[i];
this.buf[i] = undefined;
this.count--;
return v;
}
private grow(): void {
const items = Array.from({ length: this.count }, (_, i) => this.buf[this.at(i)]);
this.buf = [...items, ...new Array(items.length)];
this.head = 0;
}
toArray(): T[] {
return Array.from({ length: this.count }, (_, i) => this.buf[this.at(i)] as T);
}
}
export function demo(): string[] {
const q = new Deque<string>(2);
for (const job of ["job1", "job2", "job3"]) q.pushBack(job); // used as a queue
const lines = [`queue: [${q.toArray().join(", ")}], dequeue → ${q.popFront()}`];
q.pushFront("urgent"); // a deque can jump the line
lines.push(`after pushFront: [${q.toArray().join(", ")}], popBack → ${q.popBack()}`);
const big = new Deque<number>();
const t0 = performance.now();
for (let i = 0; i < 200_000; i++) big.pushBack(i);
while (big.size) big.popFront();
lines.push(`200 000 enqueues and dequeues in ${(performance.now() - t0).toFixed(1)} ms`);
return lines;
}When to use it
Use it when
- Work should be processed in arrival order: job queues, request buffers, message handling.
- Breadth-first search and level-order traversals.
- A deque for sliding windows (such as the running maximum of the last k values) and for undo with a size limit.
Avoid it when
- The most urgent item should go first: use a priority queue (binary heap).
- You need the most recent item: use a stack.
- Work must survive restarts or be shared between services: use a message queue such as SQS, RabbitMQ or Kafka.
Pitfalls
shift()in a hot loop, turning an O(n) algorithm into O(n²).- Unbounded queues that grow until memory runs out when producers outpace consumers. Add limits and back-pressure.
- Confusing queue and stack order, which silently changes BFS into something else.
Alternatives
Stack
Choose it when the most recent item should be handled first.
Priority queue (binary heap)
Choose it when items have priorities rather than arrival order.
Ring buffer
Choose it when the queue has a fixed maximum size.