FastPrepEvaluate a Nested Math Expression
Problems/Evaluate a Nested Math Expression

Evaluate a Nested Math Expression

Google logoGoogle● MediumFULLTIMENEW GRADPHONE SCREENONSITE INTERVIEW
QuestionFunctionExamplesConstraints

Problem statement

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.

Function

evaluateExpression(s: String) → int

Examples

Example 1

s = "add(1,sub(1,0))"return = 2

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

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.

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

  • Apartment Housemate PreferencesPHONE SCREEN · Seen Nov 2026
  • Apartment Housemate PreferencesPHONE SCREEN · Seen Nov 2026
  • Price at Query TimestampsPHONE SCREEN · Seen Nov 2026
All Google interview questionsSee Google hiring insights
Saved
class Solution {
    public int evaluateExpression(String s) {
        // write your code here
    }

}
Checking account…