1192. Flat Precedence Calculator

Medium3.5 points estimatedStackStringRecursion

A tiny scoreboard calculator treats every operator alike. The string expr holds non-negative integers, the operators +, - and *, parentheses and spaces. All three operators have the same precedence and apply strictly from left to right, while parentheses still group: 2 + 3 * 4 is 20 but 2 + (3 * 4) is 14.

Return the value as a long. The expression is always valid, has no unary minus, and the absolute value of every intermediate result is at most 10^15, so 64-bit arithmetic is enough. Spaces may appear anywhere between tokens but never inside a number.

Scan once with a stack of saved (accumulator, pending operator) pairs, one per open parenthesis, for O(n) time and O(n) space. Nesting can reach thousands of levels, so avoid deep recursion.

Example 1

Input:
expr = "2 + 3 * 4"
Output:
20
Explanation:

Operators apply strictly left to right, so (2 + 3) * 4 = 20.

Example 2

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

The parentheses group 3 * 4 = 12 first, then 2 + 12 = 14.

Example 3

Input:
expr = "(1 + 2) * (3 - 4) * 5"
Output:
-15
Explanation:

The groups give 3 and -1, so 3 * -1 = -3 and -3 * 5 = -15.

Constraints

1 ≤ expr.length ≤ 104

valid expression, no unary minus

every intermediate |value| ≤ 1015

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…