Compute Arithmetic Expression with Operator Precedence
Stacks & QueuesAuto-graded · 24 test casesLast updated
Tests parsing and evaluating mathematical expressions with proper operator precedence and parentheses using stack-based techniques.
Problem Statement
You are given a string expr representing a valid arithmetic expression. Your task is to compute and return the integer result of evaluating this expression.
The expression may contain:
- Non-negative integers (including multi-digit numbers)
- Binary operators:
+,-,*,/ - Parentheses:
(and) - Whitespace characters (which should be ignored)
Evaluation rules:
- Multiplication (
*) and division (/) have higher precedence than addition (+) and subtraction (-) - Operators with the same precedence are evaluated left-to-right (for example,
8-3-2equals(8-3)-2 = 3, not8-(3-2) = 7) - Parentheses override normal precedence and can be nested
- Division performs integer division truncating toward zero:
7 / 2 = 3(positive result)-7 / 2 = -3(negative result truncates toward zero, not floor division which would give-4)- When dividing values with different signs, compute
abs(a) / abs(b)and negate the result
- The expression is always valid with balanced parentheses and no syntax errors
- There are no unary operators (no standalone negative signs like
-5)
Constraints
1 <= expr.length <= 3 * 10^5exprconsists only of digits0-9, operators+,-,*,/, parentheses(,), and spaces- All intermediate results fit within a 32-bit signed integer
- The expression is guaranteed to be valid
Examples
Example 1
Input: compute_expression('3+2*2')
Output: 7
Example 2
Input: compute_expression('(1+(4+5+2)-3)+(6+8)')
Output: 23
Example 3
Input: compute_expression('12 / 5 + 7 * (3 - 1)')
Output: 16
Example 4
Input: compute_expression('((20-7)/3)+2*4')
Output: 12
Hints
Hint 1
Consider using two stacks: one for numeric values and another for operators and parentheses to handle precedence correctly.
Hint 2
When you encounter an operator, think about which pending operators must be executed first based on precedence rules.
Hint 3
Be careful with division - Python's // operator floors the result, but you need truncation toward zero. For negative results, this makes a difference.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Solution Approach
This problem requires correctly parsing an arithmetic expression while respecting operator precedence and parentheses. The most elegant solution uses a two-stack algorithm inspired by the shunting-yard approach.
Core Strategy
Maintain two stacks:
- Values stack: holds operands and intermediate results
- Operators stack: holds pending operators and open parentheses
Process the expression character by character from left to right:
- Digit: Accumulate the complete multi-digit number and push it onto the values stack
- Open parenthesis
(: Push it onto the operators stack as a precedence barrier - Close parenthesis
): Apply all operators back to the matching(, then remove the( - Operator: Before pushing the new operator, apply all operators on the stack that have greater-or-equal precedence (this ensures left-to-right evaluation for same-precedence operators). Then push the new operator
- Whitespace: Skip it
After scanning the entire expression, apply any remaining operators. The final value on the values stack is the answer.
Why This Works
The key insight is maintaining an invariant: operators on the stack have strictly increasing precedence between parenthesis barriers.
When a new operator arrives:
- Operators with higher precedence must execute first (e.g., in
3+2*5, the*must run before+) - Operators with equal precedence must execute left-to-right (e.g.,
8-3-2evaluates as(8-3)-2 = 3) - Operators with lower precedence wait on the stack
Using >= instead of > in the precedence comparison ensures left associativity.
Parentheses act as barriers: operators inside never interact with operators outside until the closing ) triggers evaluation of the entire subexpression.
Division Detail
Python's // operator performs floor division, but we need truncation toward zero. For negative results, these differ: -7 // 2 = -4 (floor) vs -3 (truncation). The solution computes abs(left) // abs(right) and applies the correct sign when exactly one operand is negative.
Complexity Analysis
- Time Complexity: O(n) where n is the length of the expression. Each character is examined once, and each operator is pushed and popped exactly once.
- Space Complexity: O(n) in the worst case for deeply nested parentheses or long operator chains.
Implementation
def compute_expression(expr: str) -> int:
values = []
operators = []
precedence = {'+': 1, '-': 1, '*': 2, '/': 2}
def apply_top():
op = operators.pop()
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.isspace():
i += 1
elif ch.isdigit():
value = 0
while i < n and expr[i].isdigit():
value = value * 10 + ord(expr[i]) - ord('0')
i += 1
values.append(value)
elif ch == '(':
operators.append(ch)
i += 1
elif ch == ')':
while operators[-1] != '(':
apply_top()
operators.pop()
i += 1
else:
while (operators and operators[-1] != '(' and
precedence[operators[-1]] >= precedence[ch]):
apply_top()
operators.append(ch)
i += 1
while operators:
apply_top()
return values[0]