Skip to content
RED SAGSkills
hard60 ptsstackstrings

Evaluate a Nested Expression

Evaluate an arithmetic expression containing non-negative integers, +, -, *, /, parentheses and spaces. - may also be a unary minus (for example -(2+3) or 4*-2). * and / bind tighter than + and -, equal precedence goes left to right, and division truncates toward zero.

The expression is valid and never divides by zero. Do not use eval or Function.

Example 1

Input: expr = "2*(3+4)"
Output: 14

Example 2

Input: expr = "-(2+3)*2"
Output: -10

Constraints

  • 1 <= expr.length <= 3 * 10^4
  • Parentheses nest at most 2000 levels deep.
  • Every intermediate result fits in a safe integer.
Hint 1

Use two stacks, one for numbers and one for operators, and reduce while the operator on top has higher or equal precedence.

Hint 2

A - is unary when it appears where an operand is expected: at the start, after ( or after another operator.

Hint 3

Recursion on parentheses also works, but deep nesting favours an explicit stack.

Good practice for: Frontend Developer, Backend Developer, Full Stack Developer, Mobile App Developer, Automation Test Engineer, Blockchain Developer, Data Engineer

Run checks your code on 2 sample tests. Submit runs all 10 tests, including hidden ones, and earns points. Use console.log to debug. Python's first run can take a few seconds while it starts.