Stack Use Cases
- Parentheses matching
- DFS (iterative)
- Undo/redo operations
- Function call simulation
- Monotonic stack (Hard)
- Expression evaluation
Queue Use Cases
- BFS traversal
- Task scheduling (FIFO)
- Sliding window maximum (deque)
- Level-order tree traversal
- 0-1 BFS (shortest path)
- Stream processing
A stack that maintains elements in monotonically increasing or decreasing order. Whenever we push, we pop all elements that violate the ordering. This finds the "next greater/smaller element" for every position in O(n).
Watch the stack grow and shrink as we scan {[()]} then (). Openers (purple) push to stack. Closers match the top and pop (green). Mismatch or non-empty stack at the end → invalid.
🧠 Under the Hood
Both std::stack and std::queue are container adapters wrapping a deque by default. The underlying deque uses a doubly-linked list of fixed-size chunks, giving O(1) amortized push/pop at both ends with no contiguous-memory copies.
⚖️ When to Use / When NOT to Use
vector. Stack hides all elements except the top.priority_queue (heap). FIFO order is incompatible with priority-based extraction.🚫 Common Misconceptions
stack<int, vector<int>> for better cache performance.🎤 Interview Follow-ups
3[a2[bc]], decode to abcbcabcbc. Brackets can nest arbitrarily deep.[: push current k and cur, reset both. On ]: pop, repeat cur k times, prepend prev string.