1707. Function Call Calculator

Hard7.5 points estimatedStackStringRecursionMaths

A spreadsheet cell holds a formula string expr made of non-negative integers, the binary operators +, -, * and /, unary minus, parentheses, and three function calls: max(e1, e2, ...) and min(e1, e2, ...) take one or more comma-separated arguments, and abs(e) takes exactly one; every argument is itself a full expression. Spaces may appear between tokens.

Return the value of expr as a long. Unary minus binds tighter than * and /, which bind tighter than + and -; binary operators are left-associative. Division truncates toward zero, so -7 / 2 is -3. Parenthesised groups and calls can be nested up to 500 levels deep, so a solution that recurses once per level must be careful; operator and operand stacks avoid the problem. Every intermediate value stays within [-10^15, 10^15] and no division by zero occurs. Target O(n) time and O(n) space.

Example 1

Input:
expr = "2 + 3 * max(4, 1 + 2)"
Output:
14
Explanation:

max(4, 1 + 2) is 4, then 3 * 4 = 12 and 2 + 12 = 14.

Example 2

Input:
expr = "abs(-7) - min(10, 3 * 2)"
Output:
1
Explanation:

abs(-7) is 7 and min(10, 3 * 2) is 6, so the result is 7 - 6 = 1.

Example 3

Input:
expr = "-7 / 2 * 2 + 9 / 4"
Output:
-4
Explanation:

Unary minus binds first and division truncates toward zero: -7 / 2 is -3, times 2 is -6, and 9 / 4 is 2, giving -4.

Constraints

1 ≤ expr.length ≤ 104

Spaces are allowed between tokens

Nesting depth ≤ 500

Every intermediate value lies in [-1015, 1015]

No division by zero

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.

Expected complexity

Time
O(n)
Space
O(n)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…