A double-ended queue: push and pop at both the front and the back, each in O(1) — a stack and a queue in one.
A deque — short for *double-ended queue*, said 'deck' — is a line you can add to or remove from at either end, the front or the back, each in constant time. That flexibility makes it a stack and a queue rolled into one: restrict yourself to one end and it behaves LIFO like a stack; use the front and back the usual way and it behaves FIFO like a queue.
pushBack + popBack → a stack. Use pushBack + popFront → a queue. The deque is the superset: anything a stack or queue can do, it can do, plus operations on the other end.A deque's signature use is the sliding-window maximum: find the largest value in every window of size k as it slides across an array. Naively that's O(nk). A deque holding indices, kept in decreasing order of their values, solves it in O(n). The front always holds the index of the current window's maximum.
i, popBack while the value there is ≤ arr[i] — those can never be the max again.i.≤ i − k).function maxSlidingWindow(arr, k) {
const dq = []; // holds indices, values decreasing front->back
const out = [];
for (let i = 0; i < arr.length; i++) {
while (dq.length && arr[dq[dq.length - 1]] <= arr[i]) dq.pop();
dq.push(i); // pushBack
if (dq[0] <= i - k) dq.shift(); // popFront if out of window
if (i >= k - 1) out.push(arr[dq[0]]); // front = window max
}
return out;
}collections.deque) uses a linked block structure for exactly this reason.