Evaluate Simple Arithmetic String Expressions
Stacks & QueuesAuto-graded · 17 test casesLast updated
Tests ability to evaluate a string expression containing non-negative integers, +, -, *, / operators, and parentheses using a stack-based approach.
Evaluate Simple Arithmetic String Expressions
You are given a string expr representing a valid arithmetic expression. The expression may contain:
- Non-negative integer literals (one or more digits)
- The four binary operators:
+,-,*,/ - Parentheses
(and)for grouping - Single space characters anywhere between tokens
Your task is to evaluate the expression and return the integer result.
Division is integer division that truncates toward zero (same behaviour as Python's int(a / b) — not floor division). For example, 7 / 2 = 3 and -7 / 2 = -3.
Operator precedence follows standard rules: * and / bind more tightly than + and -. Parentheses override precedence in the usual way.
You may not use Python's eval or compile built-ins.
Constraints
1 ≤ len(expr) ≤ 2 000- The expression is always syntactically valid.
- All integer literals in the expression are in the range
[0, 10 000]. - The final result and all intermediate results fit in a 32-bit signed integer (
[-2 147 483 648, 2 147 483 647]). - The expression contains only the characters
0-9,+,-,*,/,(,), and space. - There are no unary minus signs; every
-is a binary operator between two values.
Examples
Example 1
Input: evaluate_expression('3 + 5')
Output: 8
Example 2
Input: evaluate_expression('10 + 2 * 6')
Output: 22
Example 3
Input: evaluate_expression('( 2 + 3 ) * ( 8 - 3 )')
Output: 25
Hints
Hint 1
Tokenize the string first into numbers and operator/bracket tokens, then process them; this separates concerns cleanly.
Hint 2
A classic two-stack approach works well: one stack for numbers (operands) and one stack for operators. When you see a ')', pop and apply operators until you reach the matching '('.
Hint 3
To respect precedence without recursion, apply a pending higher-precedence operator (* or /) immediately when you push a lower-precedence operator (+ or -) onto the operator stack.
Worked solution
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Key Insight: Two-Stack Shunting
The standard way to evaluate an infix expression respecting precedence (without converting to postfix first) is the two-stack algorithm:
- Operand stack holds integer values seen so far.
- Operator stack holds operators and open parentheses.
When processing each token:
- Number → push onto the operand stack.
(→ push onto the operator stack as a sentinel.)→ repeatedly pop and apply operators from the operator stack until we reach the matching(, then discard the(.- Operator (
+,-,*,/) → before pushing, pop and apply all operators on top of the stack whose precedence is ≥ the current operator's precedence. This ensures higher-precedence operations are resolved before a lower-precedence one is recorded.
After all tokens are processed, apply any remaining operators.
Precedence
*,/→ level 2+,-→ level 1(→ level 0 (never popped by a normal operator check)
Division toward zero
Python's // operator floors (so -7 // 2 = -4), but the problem requires truncation toward zero (-7 / 2 = -3). We use int(a / b) which truncates.
Why It Is Correct
At every step we maintain the invariant that the operator stack is ordered by non-decreasing precedence from bottom to top (ignoring ( sentinels). When a lower-or-equal precedence operator arrives, we flush the stack of all higher-or-equal ones, preserving left-to-right associativity. Parentheses create a fresh "scope" by using ( as an impenetrable barrier.
Complexity
- Time: O(n) — each token is pushed and popped from the stacks at most once.
- Space: O(n) — both stacks together hold at most O(n) elements.
def evaluate_expression(expr: str) -> int:
import re
def precedence(op: str) -> int:
if op in ('+', '-'):
return 1
if op in ('*', '/'):
return 2
return 0
def apply_op(operands, operators):
op = operators.pop()
b = operands.pop()
a = operands.pop()
if op == '+':
operands.append(a + b)
elif op == '-':
operands.append(a - b)
elif op == '*':
operands.append(a * b)
elif op == '/':
operands.append(int(a / b))
tokens = re.findall(r'\d+|[+\-*/()]', expr)
operands = []
operators = []
for token in tokens:
if token.lstrip('-').isdigit():
operands.append(int(token))
elif token == '(':
operators.append(token)
elif token == ')':
while operators and operators[-1] != '(':
apply_op(operands, operators)
operators.pop()
else:
while (operators and operators[-1] != '(' and
precedence(operators[-1]) >= precedence(token)):
apply_op(operands, operators)
operators.append(token)
while operators:
apply_op(operands, operators)
return operands[0]