Technique
Stack for Matching & Expression Parsing
Use a plain LIFO stack to match nested structures (brackets, tags, decode strings) and evaluate expressions with precedence.
UnlocksMonotonic Stack
0%
mastery
0/13 solved
0/13 solved
Recognise it
The signal
valid/minimum-remove parentheses
1Brute force
Repeatedly find and remove innermost pairs: O(n2).
2The observation
Rescanning: the most recent unmatched opener is always on top.
3Why it works
The stack holds exactly the unmatched / unevaluated items in order.
Reach for it when
- +evaluate RPN or infix with + - * / and parentheses
- +nested encodings like 3[a2[c]]
- +path simplification, collisions
Not when
- ×needs next greater/smaller (mono-stack invariant)
- ×balance counting suffices (one counter)
Practice
0/13 solved
- Valid ParenthesesAmazon, MetaEasy
- Backspace String CompareGoogle, MetaEasy
- Move BracketsCodeforces1000
- Basic Calculator IIMeta, StripeMedium
- Decode StringGoogle, AmazonMedium
- Evaluate Reverse Polish NotationAmazon, LinkedInMedium
- Minimum Remove to Make Valid ParenthesesMeta, UberMedium
- Simplify PathMeta, MicrosoftMedium
- Asteroid CollisionUber, AmazonMedium
- Design Browser HistoryUber, MetaMedium
- Asteroid Collision (variant)NutanixOAMedium
- Array BurstGoldman SachsOAMedium
- Basic CalculatorUber, StripeHard
Pitfalls
Misconceptions
- !unary minus and operator precedence handling
Looks like it, isn't
- Valid Parenthesis String needs Greedy
Why
'*' makes stacks branch; track a range [lo, hi] of open counts. source ↗