Data Structures · Visualization
Deque: Introduction
Deque
A deque (short for 'double-ended queue', pronounced 'deck') is a collection that allows adding and removing items from both ends — front and back. Time: O(1) for push/pop at either end. Space: O(n).
Big-O: Push/pop at both ends in O(1).
Deque: Introduction
DequeA deque (short for 'double-ended queue', pronounced 'deck') is a collection that allows adding and removing items from both ends — front and back. It combines the abilities of a stack and a queue in one structure, so it can behave like either depending on which operations you use.
How Deque: Introduction Works
- Keep track of both the 'front' and the 'back' of the collection.
- Allow pushing a new item onto the front or the back.
- Allow popping (removing) an item from the front or the back.
- Optionally, peek at either end without removing anything.
Deque: Introduction Worked Example
Input: pushBack(1), pushFront(2), pushBack(3)
- pushBack(1) → [1]
- pushFront(2) → [2, 1]
- pushBack(3) → [2, 1, 3]
Output: [2, 1, 3]
Press ▶ Run to watch it step by step.
from collections import deque
d = deque()
d.append(1) # push back
d.appendleft(2) # push front
d.pop() # pop back
d.popleft() # pop front
# O(1) at both ends
# example: intro 1 on [1, 2, 3]Deque: Introduction Time & Space Complexity
When to Use Deque: Introduction
- Sliding window problems (e.g. sliding window maximum)
- Implementing both stacks and queues with a single structure
- Browser history that supports moving both forward and backward
- Undo/redo systems and job-stealing schedulers
Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Ready for the next step?
See the same ideas in action — visualize the algorithms that operate on these structures, or take a guided course.