Problem · Stack

Evaluate a Nested Math Expression

MediumGoogleFULLTIMENEW GRADONSITE INTERVIEW
See Google hiring insights

You are given a string s representing a nested arithmetic expression.

The expression uses function-call syntax:

  • add(x, y) evaluates to x + y.
  • sub(x, y) evaluates to x - 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.

Examples
01 · Example 1
s = "add(1,sub(1,0))"
return = 2

sub(1,0) = 1, then add(1,1) = 2.

02 · Example 2
s = "add(sub(5,2),sub(1,4))"
return = 0

sub(5,2) = 3 and sub(1,4) = -3, so the result is 0.

03 · Example 3
s = "sub(add(7,8),sub(3,1))"
return = 13
Constraints
  • 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.
More Google problems
drafts saved locally
public int evaluateExpression(String s) {
    // write your code here
}
s"add(1,sub(1,0))"
expected2
checking account