Problem Brief
Evaluate a Nested Math Expression
FULLTIMENEW GRADONSITE INTERVIEW
See Google online assessment and hiring insightsYou are given a string s representing a nested arithmetic expression.
The expression uses function-call syntax:
add(x, y)evaluates tox + y.sub(x, y)evaluates tox - y.
Each argument x or y is either an integer or another nested add/sub expression. The expression is guaranteed to be syntactically valid.
Return the integer value of the expression.
1Example 1
Input
s = "add(1,sub(1,0))"
Output
2
Explanation
sub(1,0) = 1, then add(1,1) = 2.
2Example 2
Input
s = "add(sub(5,2),sub(1,4))"
Output
0
Explanation
sub(5,2) = 3 and sub(1,4) = -3, so the result is 0.
3Example 3
Input
s = "sub(add(7,8),sub(3,1))"
Output
13
Constraints
Limits and guarantees your solution can rely on.
1 <= s.length <= 2 * 10^5- Integer literals fit in a 32-bit signed integer.
- The input expression is valid and contains only
add,sub, integer literals, parentheses, commas, and optional spaces. - The final result fits in a 32-bit signed integer.