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 return 14 (not 20, due to operator precedence)
  • "(2+3)*4" should return 20
  • "10-2*3" should return 4

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
Expression Evaluator Problem OverviewINPUTMathematical Expression"2+3*4"Contains:• Numbers: 2, 3, 4• Operators: +, *• Precedence: * before +Challenge:Left-to-right: 2+3=5, 5*4=20 ❌Precedence: 3*4=12, 2+12=14 ✓ALGORITHMTwo Stacks Method1Create operand & operator stacks2Scan left-to-right, push operands3Check operator precedence4Pop & calculate when neededOperands: [2]Operators: [+]Operands: [2,12]Operators: [+]RESULTFinal Answer14Correct result withproper precedence✓ 3*4 = 12 first✓ 2+12 = 14 secondTime: O(n)Space: O(n)Key Insight:Two stacks naturally handle operator precedence by comparing current operatorwith stack top - push when higher precedence, pop and calculate when lower.TutorialsPoint - Expression Evaluator | Two Stacks Algorithm
Asked in
Google 45 Amazon 38 Microsoft 32 Apple 25
34.2K Views
High Frequency
~25 min Avg. Time
856 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen