Queues & Deques
First-in, first-out queues, double-ended deques and circular buffers — the backbone of BFS, scheduling and streaming.
A queue is first-in, first-out (FIFO): add at the back (enqueue), remove from the front (dequeue) — like a line at a ticket counter. A deque ("deck", double-ended queue) allows adding and removing at both ends.
Operations
| Operation | Queue | Deque | Time |
|---|---|---|---|
| Add back | offer / enqueue | addLast | O(1) |
| Remove front | poll / dequeue | pollFirst | O(1) |
| Add front | — | addFirst | O(1) |
| Remove back | — | pollLast | O(1) |
| Peek | peek | peekFirst / peekLast | O(1) |
Circular buffer (ring buffer)
A fixed-size array with head and tail indices that wrap around with modulo. Both ends are O(1) and nothing ever shifts. This is how ArrayDeque, network packet buffers, audio buffers and logging queues work.
class CircularQueue {
private final int[] buf;
private int head = 0, size = 0;
CircularQueue(int capacity) { buf = new int[capacity]; }
boolean enqueue(int x) {
if (size == buf.length) return false; // full
buf[(head + size) % buf.length] = x;
size++;
return true;
}
Integer dequeue() {
if (size == 0) return null; // empty
int x = buf[head];
head = (head + 1) % buf.length;
size--;
return x;
}
}class CircularQueue:
def __init__(self, capacity: int):
self.buf = [None] * capacity
self.head = 0
self.size = 0
def enqueue(self, x) -> bool:
if self.size == len(self.buf):
return False
self.buf[(self.head + self.size) % len(self.buf)] = x
self.size += 1
return True
def dequeue(self):
if self.size == 0:
return None
x = self.buf[self.head]
self.head = (self.head + 1) % len(self.buf)
self.size -= 1
return xclass CircularQueue<T> {
private buf: (T | undefined)[];
private head = 0;
private size = 0;
constructor(capacity: number) { this.buf = new Array(capacity); }
enqueue(x: T): boolean {
if (this.size === this.buf.length) return false;
this.buf[(this.head + this.size) % this.buf.length] = x;
this.size++;
return true;
}
dequeue(): T | undefined {
if (this.size === 0) return undefined;
const x = this.buf[this.head];
this.head = (this.head + 1) % this.buf.length;
this.size--;
return x;
}
}Built-in queues and deques
import java.util.*;
Queue<Integer> q = new ArrayDeque<>();
q.offer(1); q.offer(2);
q.poll(); // 1
Deque<Integer> dq = new ArrayDeque<>();
dq.offerFirst(1); dq.offerLast(2);
dq.pollLast(); // 2
// Thread-safe producer/consumer queue
BlockingQueue<String> jobs = new LinkedBlockingQueue<>();from collections import deque
q = deque()
q.append(1); q.append(2)
q.popleft() # 1 — O(1)
dq = deque([1, 2, 3], maxlen=3) # bounded ring buffer
dq.appendleft(0) # drops 3 from the right
dq.rotate(1)
import queue # thread-safe: queue.Queue// JS has no built-in deque. For BFS, an index pointer works great:
const q: number[] = [1, 2, 3];
let head = 0;
while (head < q.length) {
const x = q[head++]; // O(1) "dequeue", no shift
// ... q.push(next) ...
}Where queues appear
- Breadth-first search — explore level by level. See Tree BFS.
- Scheduling — OS ready queues, print spoolers, thread pools. See CPU Scheduling.
- Buffers between producers and consumers — keyboard input, network packets, message queues like Kafka and RabbitMQ (Message queues).
- Sliding window maximum — a monotonic deque gives O(n). See Sliding window.
- Priority queues are a different structure (a heap) — they dequeue by priority, not arrival order.
- Queue = FIFO; deque = both ends; all core operations O(1).
- Implement with a circular buffer or linked list — never by shifting an array.
- Queues power BFS, schedulers and producer/consumer pipelines.
QImplement a stack using queues.easy
With one queue: on push(x), enqueue x, then rotate the previous size−1 elements behind it (dequeue + enqueue). Now the front is the most recent element: push O(n), pop O(1).
QHow do you distinguish 'full' from 'empty' in a circular buffer?medium
When head == tail, it could be either. Fixes: keep an explicit size counter (as above), or always leave one slot empty so full is (tail + 1) % cap == head.
QSliding window maximum in O(n).hard
Keep a deque of indices with decreasing values. For each new index: pop from the back while its value ≤ the new value; push the new index; pop the front if it fell out of the window. The front is always the window's maximum. Each index is pushed and popped once.