Stacks are useful whenever you need to track "the most recent" item or reverse the order of operations. Here are the most common patterns you'll encounter in interviews.
Pattern 1: Matching Parentheses
The classic stack problem: check if brackets are properly matched and nested. Push opening brackets, pop when you see closing brackets.
Pattern 2: Evaluate Expressions
Stacks are essential for evaluating mathematical expressions. Reverse Polish Notation (postfix) is especially clean with a stack.
For infix expressions (normal notation), use two stacks: one for operators and one for operands.
Pattern 3: Reversing
Stacks naturally reverse order since LIFO means first-in is last-out.
Pattern 4: Next Greater Element
Find the next element that is greater than the current one. This uses a monotonic decreasing stack.
Similarly, you can find the previous greater element by iterating from right to left, or find smaller elements by reversing the comparison.
Pattern 5: DFS Using Stack
Depth-first search can be implemented iteratively using an explicit stack instead of recursion. This avoids stack overflow for deep graphs.
Pattern 6: Min Stack
Design a stack that supports push, pop, and getMin all in O(1). The trick is to maintain a second stack that tracks the minimum at each level.
Pattern 7: Decode String
Use a stack to handle nested patterns like "3[a2[c]]" → "accaccacc".
Pattern 8: Daily Temperatures
Given daily temperatures, find how many days until a warmer day. This is a variation of "next greater element".
Common Interview Tips
Always check if stack is empty: Before calling pop() or accessing the top, verify the stack isn't empty.
Think about what to store: Sometimes you store values, sometimes indices, sometimes tuples of (value, extra_info).
Monotonic stacks: For "next greater/smaller" problems, maintain a stack in sorted order.
Nested structures: When you see brackets or nested patterns, think stack immediately.