What is a Double-Ended Queue (Deque)?
A deque drops the "only one end" restriction of a normal queue: you can insert or remove elements at both the front and the rear, and both directions stay O(1).
Key Characteristics
Deques have these fundamental properties:
- Two open ends:
- Supports operations at both front and rear
- Four core operations:
- addFront() - Insert at front
- addRear() - Insert at rear
- removeFront() - Delete from front
- removeRear() - Delete from rear
- Hybrid nature:
- Combines features of both stacks and queues
How Does It Work?
Both ends are live. Where a normal queue only lets the rear grow and the front shrink, a deque lets either pointer move in either direction. Follow this sequence on an initially empty deque:
- addRear(10): [10]
- addRear(20): [10, 20] — rear grows to the right
- addFront(5): [5, 10, 20] — front grows to the left instead
- removeRear(): Returns 20 → [5, 10]
- removeFront(): Returns 5 → [10]
Steps 2 and 3 are the whole idea: the same deque accepted a new element at the rear and then at the front, and the boxes already in it never moved. Use only addRear and removeFront and you have an ordinary FIFO queue; use only addRear and removeRear and you have a stack. That is why a deque is described as a hybrid of the two.
Time Complexity
- addFront(): O(1)
- addRear(): O(1)
- removeFront(): O(1)
- removeRear(): O(1)
- peekFront(): O(1)
- peekRear(): O(1)
Every operation touches only a pointer at one end, never the elements in between, so all six stay flat as the deque grows:
Applications
Deques are used in:
- Undo/Redo operations: Store history at both ends
- Palindrome checking: Compare front and rear elements
- Steal algorithms: Work stealing in parallel processing
- Sliding window problems: Efficient maximum/minimum tracking
- Browser history: Navigation in both directions
Special Cases
Interesting deque variations:
- Input-Restricted Deque: Insertion only at one end
- Output-Restricted Deque: Deletion only at one end
- Palindrome Checker: Using deque properties
- Priority Deque: Combines deque and priority queue features
Because it can act like a stack from one end and a queue from the other, a deque is genuinely a hybrid of the two. That flexibility is exactly why it turns up in algorithms that need fast access to both ends of a dataset at once.