Stacks and Queues
Use LIFO and FIFO structures for matching brackets, evaluating expressions, simulating processes and designing min-stacks and queues.
Beginner · about 5 hours · difficulty 2/5
Learn first: Linked Lists
Stacks and queues are simple structures that show up as building blocks in many problems and as design questions on their own.
Stack patterns
- Matching: Valid Parentheses, Minimum Add to Make Parentheses Valid.
- Expression evaluation: Evaluate Reverse Polish Notation, infix to postfix conversion, Basic Calculator.
- Undo and history: Simplify Path, Backspace String Compare, Decode String.
- Design: Min Stack (store pairs of value and current min), Implement Queue using Stacks (amortised O(1)), Implement Stack using Queues.
Queue patterns
- BFS (used heavily in trees and graphs).
- Simulation: Number of Recent Calls, Time Needed to Buy Tickets.
- Deque: push and pop at both ends; used for sliding window maximum and 0-1 BFS.
- Circular queue implementation with an array and two indices.
Pitfalls
- Popping from an empty stack. Always check before popping.
- Using a Java Stack class (synchronised, slow) instead of ArrayDeque.
- Using a Python list as a queue with pop(0).
You are ready to move on when you can implement Min Stack with O(1) getMin and explain the amortised cost of a queue built from two stacks.
Key concepts
- Stack and queue operations
- Bracket matching
- Expression evaluation
- Min Stack design
- Queue using stacks
- Deque
- Circular queue
Mini project
Solve these 10 in 7 days, log time and pattern: Valid Parentheses, Min Stack, Implement Queue using Stacks, Implement Stack using Queues, Evaluate Reverse Polish Notation, Backspace String Compare, Simplify Path, Decode String, Design Circular Queue, Basic Calculator II.
Check yourself
How does Min Stack return the minimum in O(1) even after the current minimum is popped?
Free resources
- VisuAlgo: stack and queue (VisuAlgo)
- NeetCode roadmap: Stack (NeetCode)
- takeUforward (takeUforward)