← Questions

Evaluate nested add and sub expressions

0
GoogleUberCodingLast asked Jun 2026

Implement evaluate(expression: str) -> int, which evaluates a string written in a small function-call language.

An expression is either:

  • an integer literal, possibly negative, such as 12 or -4, or
  • a function call name(arg1, arg2, ...), where each argument is itself an expression.

Two functions exist:

  • add(a, b, ...) returns the sum of all its arguments.
  • sub(a, b) takes exactly two arguments and returns a - b.

Calls can nest to any depth. Whitespace may appear around numbers, names, commas and parentheses and should be ignored. Raise an error for malformed input (unknown function, wrong number of arguments for sub, unbalanced parentheses, or extra characters after the expression).

Example 1

evaluate("sub(10,add(4,sub(9,6)))")  ->  3

sub(9,6) is 3, so add(4,3) is 7, and sub(10,7) is 3.

Example 2

evaluate(" add( sub(0, 8) , 20 , -2 ) ")  ->  10

Constraints

  • 1 <= len(expression) <= 10^5
  • Every intermediate result fits in a 64-bit signed integer.
  • Aim for a single pass over the string.
Write and test your solution herePython in your browser, the question's tests level by level, saved for you.Sign in to start coding