Parenthesized Integer Calculator with Unary Negation
Stacks & QueuesAuto-graded · 25 test casesLast updated
Evaluate an integer expression with +, -, *, /, parentheses and unary minus in one iterative pass, using precedence rules and division that truncates toward zero.
Parenthesized Integer Calculator with Unary Negation
You are given a string expr that holds an arithmetic formula. Compute its value and return it as an integer.
The formula may contain:
- non-negative integer literals (possibly several digits long),
- the binary operators
+,-,*and/, - opening and closing parentheses,
- the minus sign used as a unary (prefix) operator, e.g.
-(3 + 2),2 * -3, or--4, - space characters, which carry no meaning and may appear anywhere between tokens (including between a unary minus and what follows it).
Evaluation rules
- Anything inside parentheses is evaluated before the surrounding operators are applied.
*and/bind more tightly than binary+and-.- Operators of equal rank are applied from left to right, so
8 - 3 - 2is3and8 / 2 / 2is2. - A unary minus binds tighter than every binary operator: it negates the operand immediately to its right (a number, a parenthesized group, or another unary minus) before any binary operator uses that value.
- Division of integers truncates toward zero:
-5 / 2is-2and7 / -2is-3. Division by zero never occurs. - The input is always a well-formed expression. A unary plus never appears.
You must not use eval or any equivalent facility that evaluates source text. The nesting depth of parentheses may be very large (tens of thousands of levels), so the evaluation should be iterative rather than recursive.
Task
Implement evaluate_expression(expr) which returns the integer value of the expression.
Constraints
1 <= len(expr) <= 10^5exprconsists only of digits,+,-,*,/,(,)and spaces.- The expression is valid, and every intermediate and final value fits in a 32-bit signed integer.
- Do not use
eval, and avoid recursion.
Examples
Example 1
Input: evaluate_expression('3 + 2 * 2')
Output: 7
Example 2
Input: evaluate_expression('(1 + (4 + 5 + 2) - 3) + (6 + 8)')
Output: 23
Example 3
Input: evaluate_expression('- (3 + 2)')
Output: -5
Hints
Hint 1
Keep two stacks: one for numbers and one for operators (including opening parentheses). Scan the string once from left to right.
Hint 2
When a binary operator arrives, first apply any operators on top of the operator stack with precedence greater than or equal to it (stopping at an opening parenthesis), then push the new one. Using 'greater or equal' gives left-to-right evaluation.
Hint 3
Track whether the next token should be an operand. A '-' seen in that state is unary: push a special high-precedence negation operator that consumes one value. Also remember that Python's // floors, so divide absolute values and fix the sign.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Use the two-stack (shunting-yard style) technique in a single left-to-right scan:
valuesholds finished numbers.operatorsholds operators that are still waiting for their right operand, plus(markers.
Handling each character:
- Space: skip it.
- Digit: read the entire run of digits as one number and push it on
values. (: push it ontooperators. It acts as a floor that nothing inside can reduce past.): apply operators until the matching(is on top, discard it, and then immediately apply any unary negations sitting right below it (they were waiting for this whole group).- Binary operator: while the top of
operatorsis not(and has precedence greater than or equal to the new operator, apply it. Then push the new operator. - End of input: apply everything that is left.
Unary minus
Maintain a boolean expect_operand, true at the start, after (, and after any operator. If a - appears while an operand is expected, it is unary, so push a special operator u- with the highest precedence. It pops a single value and pushes its negation. Because it never pops anything on arrival, it works at the start, after (, after another operator (2 * -3), and when chained (--3).
Division
Python's // floors, which is wrong for negative results. Compute abs(a) // abs(b) and negate the quotient when the operand signs differ, giving truncation toward zero.
Why it is correct
At any moment the operators on the stack within one parenthesis level have non-decreasing precedence, and each is waiting for its right operand. When a new binary operator arrives, every stacked operator with precedence at least as high already has its right operand complete and must run first: higher precedence binds tighter, and equal precedence is resolved left first (the reason for >=). Lower-precedence operators stay on the stack until later. Parentheses serve as barriers, so a group is fully reduced to a single value by the time ) is processed. The unary operator has top precedence, so it is applied as soon as its operand is complete, and the extra step after ) handles a negation applied to a whole group. Since nothing recurses, deep nesting only grows the two lists.
Complexity
- Time: O(n), since each character is read once and each number and operator is pushed and popped at most once.
- Space: O(n) in the worst case (for example, deeply nested parentheses) for the two stacks.
Reference solution
def evaluate_expression(expr: str) -> int:
values = []
operators = []
precedence = {"+": 1, "-": 1, "*": 2, "/": 2, "u-": 3}
expect_operand = True
def apply_operator():
op = operators.pop()
if op == "u-":
values.append(-values.pop())
return
right = values.pop()
left = values.pop()
if op == "+":
values.append(left + right)
elif op == "-":
values.append(left - right)
elif op == "*":
values.append(left * right)
else:
quotient = abs(left) // abs(right)
values.append(-quotient if (left < 0) != (right < 0) else quotient)
i = 0
n = len(expr)
while i < n:
ch = expr[i]
if ch == " ":
i += 1
elif ch.isdigit():
number = 0
while i < n and expr[i].isdigit():
number = number * 10 + ord(expr[i]) - ord("0")
i += 1
values.append(number)
expect_operand = False
elif ch == "(":
operators.append(ch)
expect_operand = True
i += 1
elif ch == ")":
while operators[-1] != "(":
apply_operator()
operators.pop()
while operators and operators[-1] == "u-":
apply_operator()
expect_operand = False
i += 1
else:
if expect_operand:
if ch != "-":
raise ValueError("Invalid expression")
operators.append("u-")
else:
while (operators and operators[-1] != "(" and
precedence[operators[-1]] >= precedence[ch]):
apply_operator()
operators.append(ch)
expect_operand = True
i += 1
while operators:
apply_operator()
return values[0]