Basic Calculator II - Problem
๐งฎ Build Your Own Calculator
You're tasked with creating a mathematical expression evaluator that can handle basic arithmetic operations. Given a string s containing an expression with integers and operators (+, -, *, /), your job is to evaluate it and return the result.
Key Requirements:
- Handle operator precedence correctly (
*and/before+and-) - Integer division should truncate toward zero (not floor division)
- No built-in
eval()functions allowed - All expressions are guaranteed to be valid
Example: "3+2*2" should return 7 (not 10), because multiplication has higher precedence.
Input & Output
example_1.py โ Basic Expression
$
Input:
s = "3+2*2"
โบ
Output:
7
๐ก Note:
Multiplication has higher precedence: 3 + (2*2) = 3 + 4 = 7
example_2.py โ Division with Truncation
$
Input:
s = "3/2"
โบ
Output:
1
๐ก Note:
Integer division truncates toward zero: 3/2 = 1.5 โ 1
example_3.py โ Complex Expression
$
Input:
s = "3+5/2"
โบ
Output:
5
๐ก Note:
Division first, then addition: 3 + (5/2) = 3 + 2 = 5
Visualization
Tap to expand
Understanding the Visualization
1
Scan & Build Numbers
Read digits and build complete numbers while tracking the last operator
2
Decision Point
When encountering an operator, decide: compute now (*, /) or defer (+, -)?
3
Stack Management
High precedence ops modify stack top immediately, low precedence ops add to stack
4
Final Computation
Sum everything in the stack - all precedence has been handled!
Key Takeaway
๐ฏ Key Insight: The stack approach elegantly solves precedence by making high-precedence operations execute immediately while deferring low-precedence operations. This transforms a complex parsing problem into simple stack operations!
Time & Space Complexity
Time Complexity
O(n)
Single pass through the string, each character processed once
โ Linear Growth
Space Complexity
O(n)
Stack can contain at most n/2 numbers in worst case (alternating numbers and + operators)
โก Linearithmic Space
Constraints
- 1 โค s.length โค 3 * 105
- s consists of integers and operators ('+', '-', '*', '/') separated by some number of spaces
- s represents a valid expression
- All the integers in the expression are non-negative integers in the range [0, 231 - 1]
- The answer is guaranteed to fit in a 32-bit integer
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code