Double-ended queues
Day 137 of 149
👉 Full deep-dive with code examples
The Deck of Cards Analogy
A deck of cards in your hand:
- Add a card to the top
- Add a card to the bottom
- Take a card from the top
- Take a card from the bottom
You can work from EITHER end!
A Deque (Double-Ended Queue) lets you add and remove from both ends!
The Problem They Solve
Sometimes you need flexibility:
- Stacks: Only work from one end (top)
- Queues: Add at one end, remove from other
What if you need to add at the front sometimes AND the back other times?
How Deques Work
Think of it as a line that can grow or shrink from either side:
←← ADD HERE ADD HERE →→
Front ←[ Alice | Bob | Carol | Dan ]→ Back
←← REMOVE HERE REMOVE HERE →→
Operations:
- Add to front
- Add to back
- Remove from front
- Remove from back
All are fast (instant)!
When To Use Deques
Sliding window problems:
- Add new items at one end
- Remove old items from the other
Undo/Redo:
- Add new actions at one end
- Limit history by removing from other end
Palindrome checking:
- Compare front and back characters
- Remove from both ends as you go
Deque vs Stack vs Queue
| Operation | Stack | Queue | Deque |
|---|---|---|---|
| Add front | ✓ | ✗ | ✓ |
| Add back | ✗ | ✓ | ✓ |
| Remove front | ✓ | ✓ | ✓ |
| Remove back | ✗ | ✗ | ✓ |
Deque = most flexible!
In One Sentence
A Deque is a double-ended queue that lets you efficiently add and remove items from both the front and back.
🔗 Enjoying these? Follow for daily ELI5 explanations!
Making complex tech concepts simple, one day at a time.
Top comments (0)