Deque
A double-ended queue (deque) supports push and pop from both the front and back in O(1). It generalises both stacks and queues — and powers the sliding window maximum algorithm.
What is a deque?
A deque ("deck") is a double-ended queue: you can add and remove items at both the front and the back in O(1). It can act as a stack or a queue, and it's the key structure for sliding window maximum and many scheduling problems. Implement it with a doubly linked list or a circular buffer.
// Sliding window maximum with a deque of indices: O(n)
function maxInWindows(nums, k) {
const dq = [], out = [];
nums.forEach((n, i) => {
if (dq[0] <= i - k) dq.shift(); // left the window
while (dq.length && nums[dq.at(-1)] <= n) dq.pop(); // smaller can't be max
dq.push(i);
if (i >= k - 1) out.push(nums[dq[0]]);
});
return out;
}Operations — animated
// Array state
// Pseudocode
Complexity
Constant time
Constant time
Constant time
Linear time
Doubly-linked list implementation
1// Deque — push/pop from both ends O(1)2structure Deque:3 head: Node | null4 tail: Node | null56function pushFront(val):7 node = new Node(val)8 node.next = head9 if head: head.prev = node10 head = node11 if not tail: tail = node1213function pushBack(val):14 node = new Node(val)15 node.prev = tail16 if tail: tail.next = node17 tail = node18 if not head: head = node1920function popFront(): return remove(head)21function popBack(): return remove(tail)
Classic use: sliding window maximum
Find the maximum in every window of size k in O(n) total using a monotonic deque. The deque always stores indices of candidate maxima in decreasing value order.
1// Sliding window maximum using a deque2function maxSlidingWindow(nums, k):3 dq = Deque() // stores indices, front = max4 result = []5 for i from 0 to len(nums) - 1:6 // remove indices outside window7 while dq not empty and dq.front < i - k + 1:8 dq.popFront()9 // remove smaller elements from back10 while dq not empty and nums[dq.back] < nums[i]:11 dq.popBack()12 dq.pushBack(i)13 if i >= k - 1:14 result.append(nums[dq.front])15 return result // O(n) total
🎯 Quick Check
You implement a queue using two deques. What is the time complexity of each enqueue and dequeue?
Deque (Double-Ended Queue): summary
Key points
- Operations: pushFront, pushBack, popFront, popBack, all O(1) in a proper implementation.
- A JavaScript array's
shift/unshiftare O(n); fine for small inputs only.
Frequently asked questions
›Deque vs queue?
A queue only adds at the back and removes at the front. A deque allows both operations at both ends.