Stacks and Queues
A stack removes the most recent item. A queue removes the earliest waiting item. A deque permits operations at either end.
Picture the idea
Undo history is a stack; the list of students waiting at the laboratory printer is a queue.
When to use it
Use a stack for nested unfinished work and a queue when arrival order matters.
How it works
For brackets, push each opening symbol. A closer must match the latest unmatched opener. A successful end leaves the stack empty.
- Push, inspect and pop the top.
- Enqueue at the back and dequeue from the front.
- Discard dominated candidates from a monotone deque.
Typical endpoint operations cost O(1) or amortized O(1) depending on storage. A monotone stack scan is O(n) because each index enters and leaves once.
Watch for this mistake
A matching count alone misses the ordering error in “)(”.
Show the stack or queue after each token and say which end is active.