Evaluate nested add and sub expressions
I was asked this
No reports yet. Sign in to say where you were asked it.
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
12or-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 returnsa - 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.
Sign in to see the worked answer
The full answer, chapter by chapter, with what interviewers expect at each level. Free with an account: one full answer per company.
Sign in to see the worked answer
The full answer, chapter by chapter, with what interviewers expect at each level. Free with an account: one full answer per company.

