Skip to main content

Arithmetic Expression Solver

medium
StackStringMathStack Matching
Asked atGoogleAmazonMicrosoftMetaBloomberg

Problem Description

Given a string `expr` representing a valid arithmetic expression containing non-negative integers, the operators `+`, `-`, `*`, `/` (integer division truncating toward zero), and parentheses `(` and `)`, evaluate the expression and return its integer result.

You may **not** use any built-in expression evaluation functions (e.g., `eval`).

**Example 1:**
```
Input: expr = "3 + 5 * (2 - 8) / 2"
Output: -12
```
Explanation: 2 - 8 = -6; -6 / 2 = -3 (truncated); 5 * -3 = -15; 3 + -15 = -12.

**Example 2:**
```
Input: expr = "(4 + 6) * 3"
Output: 30
```

Constraints

  • 1 <= expr.length <= 3 * 10^4
  • expr contains only digits, spaces, '+', '-', '*', '/', '(', ')'
  • All intermediate and final results fit in a 32-bit signed integer
  • Division always truncates toward zero

Follow-up

Extend the evaluator to support unary negation (e.g., `-3 * (2 + 4)`) and the exponentiation operator `^` with right-associativity.

Hints

Try the problem first. If you get stuck, you can reveal hints one at a time.

Solution

Leaderboard

No entries yet for python.

Be the first — submit an accepted solution.