Expression Evaluator - Problem
Write a function to evaluate a mathematical expression string containing the operators +, -, *, / and parentheses () using two stacks - one for operators and one for operands.
The expression will always be valid and contain only integers, the four basic arithmetic operators, and parentheses. Division should return integer results (truncate towards zero).
Examples:
"2+3*4"should return14(not 20, due to operator precedence)"(2+3)*4"should return20"10-2*3"should return4
Input & Output
Example 1 — Basic Expression with Precedence
$
Input:
expression = "2+3*4"
›
Output:
14
💡 Note:
Multiplication has higher precedence: 3*4 = 12, then 2+12 = 14 (not 20)
Example 2 — Parentheses Override Precedence
$
Input:
expression = "(2+3)*4"
›
Output:
20
💡 Note:
Parentheses first: (2+3) = 5, then 5*4 = 20
Example 3 — Complex Expression
$
Input:
expression = "10-2*3"
›
Output:
4
💡 Note:
Multiplication first: 2*3 = 6, then 10-6 = 4
Constraints
- 1 ≤ expression.length ≤ 3 × 105
- expression consists of integers and operators (+, -, *, /, (, ))
- All intermediate calculations fit within 32-bit integers
- Division is integer division (truncate towards zero)
Visualization
Tap to expand
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code