Problem · Stack
Evaluate a Nested Math Expression
Learn this problemProblem statement
You 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.
Function
evaluateExpression(s: String) → intExamples
Example 1
s = "add(1,sub(1,0))"return = 2sub(1,0) = 1, then add(1,1) = 2.
Example 2
s = "add(sub(5,2),sub(1,4))"return = 0sub(5,2) = 3 and sub(1,4) = -3, so the result is 0.
Example 3
s = "sub(add(7,8),sub(3,1))"return = 13Constraints
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
- Deduplicate Logs: Keep FirstONSITE INTERVIEW · Seen Jul 2026
- Deduplicate Logs: Keep LatestONSITE INTERVIEW · Seen Jul 2026
- Find a Template Across Binary-Tree LeavesONSITE INTERVIEW · Seen Jul 2026
- Maximum Programmer-Problem MatchingONSITE INTERVIEW · Seen Jul 2026
- Minimum Direction ViolationsONSITE INTERVIEW · Seen Jul 2026
- Stream Latest Log VersionsONSITE INTERVIEW · Seen Jul 2026
- Stream Unique Logs in Timestamp OrderONSITE INTERVIEW · Seen Jul 2026
- Top-K IP Addresses from File RecordsONSITE INTERVIEW · Seen Jul 2026