Matching pairs
O(n)Push every opener. On a closer, the top of the stack must be its partner. At the end the stack must be empty.
Reach for it when things open and close and must nest properly.The last thing in is the first thing out. Perfect for anything that opens and must later close, or that waits until something better comes along.
3[a2[c]]. A stack holds the outer level while you deal with the inner one.Push every opener. On a closer, the top of the stack must be its partner. At the end the stack must be empty.
Reach for it when things open and close and must nest properly.When a new level opens, push what you have so far and start fresh. When it closes, pop the outer state and fold the inner result into it.
Reach for it when the input nests, and you would otherwise reach for recursion.Go deeper: What the call stack does during recursionKeep numbers on a stack. An operator pops its operands and pushes the result. Delay addition so multiplication can bind first.
Reach for it when you are evaluating arithmetic, postfix notation, or a small calculator.Compare each new item only with the top. If they cancel, pop and compare again with the new top. Otherwise push.
Reach for it when neighbours can destroy each other and the survivors form the answer.Go deeper: Amortised cost: why push is O(1) on averageKeep the stack in decreasing order. A new value pops everything smaller, and it is the answer every popped item was waiting for.
Reach for it when each element needs the next or previous larger or smaller element, or the widest span it dominates.Go deeper: Amortised cost: why push is O(1) on averageWorth knowing cold: the monotonic stack. It looks quadratic because of the inner loop, but every index is pushed and popped once.
| # | Problem | Pattern | Difficulty | Solution |
|---|---|---|---|---|
| 1 | Baseball Game | Stack simulation | Easy | Read |
| 2 | Valid Parentheses | Matching pairs | Easy | Read |
| 3 | Next Greater Element I | Monotonic stack | Easy | Read |
| 4 | Evaluate Reverse Polish Notation | Expression evaluation | Medium | Read |
| 5 | Asteroid Collision | Collapse the top | Medium | Read |
| 6 | Daily Temperatures | Monotonic stack | Medium | Read |
| 7 | Decode String | Nested levels | Medium | Read |
| 8 | Next Greater Element II | Monotonic stack | Medium | Read |
| 9 | Basic Calculator II | Expression evaluation | Medium | Read |
| 10 | Car Fleet | Monotonic stack | Medium | Read |
| 11 | Remove K Digits | Monotonic stack | Medium | Read |
| 12 | Largest Rectangle in Histogram | Monotonic stack | Hard | Read |
| 13 | Trapping Rain Water | Monotonic stack | Hard | Read |
| 14 | Basic Calculator | Nested levels | Hard | Read |