KatInterview

Parse and Compute Arithmetic Expression with Recursion

Stacks & QueuesModel answer
MediumModel answerStacks & Queuesrecursionparsingoperators

Last updated

Write a parser that evaluates arithmetic expressions with integers, four operators, parentheses, and unary negation using recursive descent or explicit stack DFS.

You are given a string containing an arithmetic expression. The expression includes:

  • Non-negative integers
  • Binary operators: +, -, *, /
  • Parentheses: ( and )
  • Unary minus (e.g., -5, -(3+2))
  • Optional whitespace

Write a function that evaluates the expression and returns the result as an integer.

Requirements:

  • Implement the solution using depth-first traversal (either recursive descent parsing or an explicit stack-based approach)
  • Respect standard operator precedence: * and / before + and -
  • All operators are left-associative
  • Division truncates toward zero: -7 / 2 equals -3
  • Handle unary minus anywhere an operand can appear: -3, 2 * -5, --4
  • Assume all intermediate results fit in a 64-bit signed integer
  • Raise an error on division by zero or malformed input

Example:

evaluate("3 + 5 * 2") → 13
evaluate("(2 + 3) * -4") → -20
evaluate("10 / -3") → -3
evaluate("-(-5)") → 5

Analyze the time and space complexity of your solution. Discuss potential issues with deep recursion and describe how an iterative approach would differ.

Hints

Hint 1

Model operator precedence as nested grammar rules where each level calls the next higher precedence level

Hint 2

Unary minus can be treated as a high-precedence operation that applies to the next factor

Hint 3

Python's // operator floors toward negative infinity, not zero—handle negative division carefully