2dbi

Evaluate a Mathematical Expression

viaLeetCode

Problem Evaluate an arithmetic expression string with +, -, *, / and nested parentheses, e.g. (((2-2)*12+22)-((22-11)*11)/2), honoring precedence.

Input / Output

  • Input: expression string. Output: numeric result.

Constraints

  • Length up to 10^4; multi-digit numbers, optional whitespace, unary minus (clarify!), integer vs float division (clarify) — the clarifications are part of the grade.

Example

  • "(3+2)2" → 10; "2+34" → 14 (precedence); "((2-2)*12+22)" → 22.

Expected approach

  • Two-stack (Dijkstra shunting-yard style): values stack + operators stack; on an operator, first apply any stacked operators of >= precedence; '(' pushes, ')' unwinds to the matching '('; drain at end. O(n)/O(n).
  • Recursive descent alternative: expr → term (+|− term), term → factor (|/ factor)*, factor → number | (expr) — cleaner to extend (unary minus, ^). Know both shapes; multi-digit parsing and precedence-while-stacking are where implementations break.
Add a follow-up question they asked
No follow-ups yet. Be the first to add one.
asked …
LeaderboardSalary
Language
Account