Evaluate Valid Expressions Problem
#3749
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 3749.
You are given a string expression that represents a nested mathematical expression in a simplified form.
A valid expression is either an integer literal or follows the format op(a,b), where:
opis one of"add","sub","mul", or"div".aandbare each valid expressions.
The operations are defined as follows:
add(a,b) = a + bsub(a,b) = a - bmul(a,b) = a * bdiv(a,b) = a / b
Return an integer representing the result after fully evaluating the expression.
Example 1:
Input: expression = "add(2,3)"
Output: 5
Explanation:
The operation add(2,3) means 2 + 3 = 5.
Example 2:
Input: expression = "-42"
Output: -42
Explanation:
The expression is a single integer literal, so the result is -42.
Example 3:
Input: expression = "div(mul(4,sub(9,5)),add(1,1))"
Output: 8
Explanation:
- First, evaluate the inner expression: sub(9,5) = 9 - 5 = 4
- Next, multiply the results: mul(4,4) = 4 * 4 = 16
- Then, compute the addition on the right: add(1,1) = 1 + 1 = 2
- Finally, divide the two main results: div(16,2) = 16 / 2 = 8
Therefore, the entire expression evaluates to 8.
Constraints:
1 <= expression.length <= 10^5expressionis valid and consists of digits, commas, parentheses, the minus sign'-', and the lowercase strings"add","sub","mul","div".- All intermediate results fit within the range of a long integer.
- All divisions result in integer values.
Solution
Approach: Recursive descent
Write parse(i), which evaluates the subexpression that starts at index i and returns its value together with the index just after it. The answer is parse(0).
- If the character at
iis a digit or-, it is an integer literal: read digits until a non-digit and return the number. - Otherwise read the operator name up to
(, parse the first argument, skip the,, parse the second argument, and skip the). Then applyadd,sub,mulordivto the two values. Every division is exact, so ordinary integer division is safe.
Each character is visited once. The recursion depth equals the nesting depth of the expression.
Complexity: time O(n), space O(n).
class Solution:
def evaluateExpression(self, expression: str) -> int:
def parse(i: int) -> (int, int):
if expression[i].isdigit() or expression[i] == "-":
j = i
if expression[j] == "-":
j += 1
while j < len(expression) and expression[j].isdigit():
j += 1
return int(expression[i:j]), j
j = i
while expression[j] != "(":
j += 1
op = expression[i:j]
j += 1
val1, j = parse(j)
j += 1
val2, j = parse(j)
j += 1
if op == "add":
res = val1 + val2
elif op == "sub":
res = val1 - val2
elif op == "mul":
res = val1 * val2
else:
res = val1 // val2
return res, j
return parse(0)[0]