Basic Calculator III
Master this topic with zero to advance depth.
Basic Calculator III
Evaluate an expression string containing (, ), +, -, *, /, non-negative integers and spaces. This is the ultimate calculator problem.
Visual Representation
s = "2*(5+5*2)/3+(6/2+8)"
1. Handle parentheses recursively or using a stack stack.
2. Within each group, apply multiply/divide first, then add/subtract.
3. Result: 2*(15)/3 + (11) = 10 + 11 = 21Examples
Input: s = "2*(5+5*2)/3+(6/2+8)"
Output: 21
Approach 1
Level III: Optimal (Recursion with Deque/Index)
Intuition
This problem combines Basic Calculator I and II. The most natural solution uses recursion to handle parentheses: every time we see (, we recurse; every time we see ), we return the result of the current sub-expression. Within each level, we use the standard 'accumulator' logic for +, -, *, /.
⏱ O(N)💾 O(N)
⚠️ Common Pitfalls & Tips
Sentinel + at the end makes the loop logic cleaner for the last number. Be careful with division truncation in Python.
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.