Deque
A deque (pronounced "deck") stands for Double-Ended Queue. It's like a regular queue, but with a superpower: you can add or remove items from both ends — the front and the back.
Imagine a train car with doors on both ends. Passengers can board from the front or the back, and they can exit from either end too. That's a deque.
Four operations — all instant
- push_front — add to the front
- push_back — add to the back
- pop_front — remove from the front
- pop_back — remove from the back
All four are \(O(1)\). Because a deque tracks both ends with pointers, there's no shifting needed.
← → arrow keys to step · click elements to interact
Stack and Queue in one
A deque is a generalization of both a stack and a queue:
- Use only push_back + pop_back → behaves like a stack (LIFO)
- Use only push_back + pop_front → behaves like a queue (FIFO)
This flexibility makes deques incredibly useful.
Sliding Window Maximum
One of the most famous uses of a deque is the sliding window maximum problem. As a window slides across an array, you need the maximum in the current window at all times. A deque tracks candidates efficiently — adding new elements at the back and removing stale ones from the front — keeping the solution to \(O(n)\) instead of \(O(n×k)\).
Palindrome checking
Deques make palindrome checking elegant. Push all characters in. Then compare pop_front with pop_back, one pair at a time. If they always match, it's a palindrome!