Evaluate Arithmetic Expression with Operator Precedence
Stacks & QueuesAuto-graded · 25 test casesLast updated
Tests implementation of expression evaluation using stacks to handle operator precedence and parentheses correctly.
Write a function that takes an arithmetic expression as a string and computes its result. The expression contains non-negative integers and the operators +, -, *, /, along with parentheses ().
Your evaluator must respect standard mathematical rules:
- Multiplication and division bind more tightly than addition and subtraction
- Operators of equal precedence associate left-to-right (so
8 - 3 - 2equals3, not7) - Parentheses override the default precedence
- Division truncates toward zero (so
7 / 2gives3, and(1 - 6) / 2gives-2)
The input is guaranteed to be a valid expression with no division by zero. Whitespace may appear anywhere and should be ignored.
Constraints
1 <= len(s) <= 10000- All integer operands are non-negative
- The expression is well-formed and contains no division by zero
- The result fits in a 32-bit signed integer
Examples
Example 1
Input: evaluate_expression('3 + 2 * 2')
Output: 7
Example 2
Input: evaluate_expression('(3 + 5) / 2')
Output: 4
Example 3
Input: evaluate_expression('12 + 3 * (4 - 2)')
Output: 18
Hints
Hint 1
Use two stacks: one for numbers and one for operators. Parentheses act as precedence barriers.
Hint 2
Before pushing a new operator, pop and apply all operators with greater or equal precedence to maintain left associativity.
Hint 3
For division with negative intermediates, divide the absolute values and then restore the correct sign to truncate toward zero.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Use a two-stack algorithm to parse and evaluate the expression in a single pass. Maintain one stack for operands and another for operators.
Process the string character by character:
- Numbers: Parse the complete multi-digit integer and push it onto the value stack
- Opening parenthesis: Push it onto the operator stack as a precedence boundary
- Closing parenthesis: Apply all operators back to the matching opening parenthesis, then discard both parentheses
- Operators: Before pushing the new operator, pop and evaluate all operators on the stack that have equal or higher precedence (this ensures left-to-right evaluation and correct precedence)
- End of input: Apply any remaining operators
The key insight is that maintaining operators in increasing precedence order (bottom to top) naturally handles precedence rules. Popping operators with equal precedence enforces left associativity.
For division, since intermediate results can be negative, we must truncate toward zero rather than floor. Divide the absolute values and restore the sign based on whether the operands have matching signs.
Correctness
The algorithm maintains an invariant: within any parenthesis level, operators on the stack have strictly increasing precedence from bottom to top. This ensures:
- High-precedence operators execute before lower-precedence ones they precede
- Equal-precedence operators execute left-to-right because we pop on equality
- Parentheses create isolated sub-problems by blocking pops with the
(marker
Complexity
Time: O(n) where n is the length of the string. Each character is visited once, and each number and operator is pushed and popped at most once.
Space: O(n) for the two stacks. Worst case occurs with deep nesting or long chains of increasing precedence.
def evaluate_expression(s: str) -> int:
s = ''.join(s.split())
values = []
operators = []
precedence = {'+': 1, '-': 1, '*': 2, '/': 2}
def apply():
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
while i < len(s):
if s[i].isdigit():
j = i + 1
while j < len(s) and s[j].isdigit():
j += 1
values.append(int(s[i:j]))
i = j
elif s[i] == '(':
operators.append(s[i])
i += 1
elif s[i] == ')':
while operators[-1] != '(':
apply()
operators.pop()
i += 1
else:
op = s[i]
while operators and operators[-1] != '(' and precedence[operators[-1]] >= precedence[op]:
apply()
operators.append(op)
i += 1
while operators:
apply()
return values[0]