Parse and Compute Arithmetic Expression with Recursion
Stacks & QueuesModel answerLast 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 / 2equals-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
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The core insight is to model operator precedence through a grammar where each precedence level becomes a parsing function. Lower-precedence operations call higher-precedence ones, naturally building the correct evaluation order through the call stack.
Grammar Structure
expression := term (('+' | '-') term)*
term := factor (('*' | '/') factor)*
factor := ('+' | '-') factor | NUMBER | '(' expression ')'
Each rule represents one precedence level:
expressionhandles addition and subtractiontermhandles multiplication and divisionfactorhandles unary operators, numbers, and parenthesized sub-expressions
The * notation means "zero or more," giving us left-associativity: 8 - 3 - 2 evaluates left-to-right as (8 - 3) - 2 = 3.
Why This Works
Precedence: When parsing 2 + 3 * 4, the expression function calls term, which fully consumes 3 * 4 before returning. The multiplication happens first, yielding 12, and only then does the addition occur.
Parentheses: The factor rule recursively calls expression when it sees (, creating a nested evaluation. The closing ) marks the boundary.
Unary Minus: Handled in factor, making it bind tighter than multiplication. This is mathematically safe: (-a) * b = -(a * b).
Division: Python's // floors toward negative infinity, but we need truncation toward zero. Solution: compute abs(a) // abs(b), then apply the correct sign based on whether the operands have matching signs.
Implementation (Recursive Descent)
def evaluate(s: str) -> int:
n = len(s)
pos = 0
def skip_spaces():
nonlocal pos
while pos < n and s[pos] == ' ':
pos += 1
def peek():
skip_spaces()
return s[pos] if pos < n else ''
def divide(a, b):
if b == 0:
raise ZeroDivisionError("division by zero")
quotient = abs(a) // abs(b)
return quotient if (a >= 0) == (b >= 0) else -quotient
def parse_expression():
nonlocal pos
result = parse_term()
while peek() in ('+', '-'):
op = s[pos]
pos += 1
right = parse_term()
result = result + right if op == '+' else result - right
return result
def parse_term():
nonlocal pos
result = parse_factor()
while peek() in ('*', '/'):
op = s[pos]
pos += 1
right = parse_factor()
result = result * right if op == '*' else divide(result, right)
return result
def parse_factor():
nonlocal pos
c = peek()
# Unary operators
if c in ('+', '-'):
pos += 1
value = parse_factor()
return -value if c == '-' else value
# Parenthesized expression
if c == '(':
pos += 1
value = parse_expression()
if peek() != ')':
raise ValueError(f"missing closing parenthesis at position {pos}")
pos += 1
return value
# Number
if c.isdigit():
start = pos
while pos < n and s[pos].isdigit():
pos += 1
return int(s[start:pos])
raise ValueError(f"unexpected character at position {pos}")
result = parse_expression()
if peek() != '':
raise ValueError(f"unexpected trailing input at position {pos}")
return result
Complexity Analysis
Time: O(n) where n is the length of the string. Each character is examined exactly once. Each operation (arithmetic or comparison) takes constant time, assuming 64-bit integers.
Space: O(d) where d is the maximum nesting depth (parentheses and unary operators). In the worst case, d can be O(n) for deeply nested input like ((((((1)))))) or ------5. The call stack grows with nesting depth.
Recursion Depth Considerations
CPython's default recursion limit is around 1000 frames. With roughly three stack frames per parenthesis level (parse_factor → parse_expression → parse_term → parse_factor), inputs with ~330 nested parentheses will hit the limit.
For production systems accepting untrusted input:
- Impose a depth limit and reject excessively nested expressions
- Use an iterative approach with an explicit stack (see below)
- Increase the recursion limit with
sys.setrecursionlimit(), though this risks stack overflow
Iterative Alternative
An iterative solution uses two explicit stacks (operands and operators) and implements the shunting-yard algorithm with immediate evaluation:
- Push numbers onto the value stack
- When encountering operators, pop higher-precedence operators first and evaluate them
- Track whether the previous token was an operand to distinguish unary from binary minus
- Use a sentinel operator
'u'with highest precedence for unary minus
The iterative version has O(1) auxiliary space per operator (not per nesting level), making it robust against deep nesting.
Common Mistakes
- Using Python's
//directly for division (gives wrong results for negatives) - Forgetting to handle unary operators
- Implementing right-associativity instead of left (making
8-3-2evaluate as8-(3-2)) - Not validating that all input was consumed (accepting
3 + 2)as valid) - Confusing unary and binary minus in edge cases like
3--5