Evaluate Valid Expressions

You are given a string expression representing a simplified nested mathematical expression.

A valid expression can be:

  • An integer literal (for example, "7" or "-15"), or
  • An expression in the form: op(a,b)

Where:

  • op is one of: "add", "sub", "mul", "div"
  • a and b are themselves valid expressions (they may be nested)

The operations behave as follows:

  • add(a,b) → a + b
  • sub(a,b) → a - b
  • mul(a,b) → a * b
  • div(a,b) → a / b

Your task is to return the final integer value after fully evaluating the given expression.

Example 1:

Input: expression = "mul(add(1,2),3)"

Output: 9

Explanation:

  • First evaluate the inner expression: add(1,2) = 3
  • Then multiply: mul(3,3) = 9
  • So the final result is 9.

Example 2:

Input: expression = "sub(add(10,5),mul(2,3))"

Output: 9

Explanation:

  • add(10,5) = 15
  • mul(2,3) = 6
  • sub(15,6) = 9

Therefore, the expression evaluates to 9.

Now Your Turn!

Pick the correct output for the given input

Input: expression = "div(add(8,4),sub(5,3))"

Still unsure what the problem is asking ?

Let’s go through a few more examples, step by step, to make it clearer.

Constraints:

1 ≤ expression.length ≤ 105

expression consists only of:

  • digits (0–9)
  • the minus sign -
  • commas ,
  • parentheses ( and )
  • lowercase strings "add", "sub", "mul", "div"

The input expression is always valid.

All intermediate and final results fit within the range of a 64-bit signed integer.

Every division operation results in an integer value (no fractional results).

Hints

Frequently Occurring Doubts

Interview Follow-up Questions

Fun Facts

0
class Solution {
public:
long long evaluateExpression(string expression) {
// Your code goes here
}
};
Test Case

Input:

Expression