Compute an Arithmetic Expression Honoring Operator Precedence
Stacks & QueuesAuto-graded · 25 test casesLast updated
Tests ability to parse and compute integer arithmetic respecting operator precedence without using eval or a full expression parser.
Write a function that evaluates a mathematical expression given as a string. The expression contains:
- Non-negative integers
- Four binary operators:
+,-,*,/ - Spaces (which should be ignored)
Your function must respect standard arithmetic precedence rules: multiplication and division are performed before addition and subtraction. Operations of equal precedence are evaluated left to right.
Division is integer division truncating toward zero. For example, 7 / 2 evaluates to 3, and -7 / 2 evaluates to -3 (not -4).
The input expression is guaranteed to be valid: it will not contain parentheses, unary operators, or malformed syntax.
Constraints:
1 <= len(s) <= 3 * 10^5sconsists of digits,'+','-','*','/', and' 'srepresents a valid arithmetic expression- All intermediate results fit in a 32-bit signed integer
- Division by zero will not occur
Examples
Example 1
Input: evaluate_expression('3+2*2')
Output: 7
Example 2
Input: evaluate_expression(' 3/2 ')
Output: 1
Example 3
Input: evaluate_expression(' 3+5 / 2 ')
Output: 5
Hints
Hint 1
Think of the expression as a sum of signed terms, where each term is a product or quotient of numbers.
Hint 2
Use a stack to store completed terms. Multiplication and division modify the most recent term; addition and subtraction add new terms.
Hint 3
Track three pieces of state: the number being built digit-by-digit, the last operator seen, and the stack of terms.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The key insight is to view the expression as a sum of signed terms, where each term is built from numbers connected by * and / operators. Since multiplication and division have higher precedence, they must be evaluated before addition and subtraction.
We scan the string once from left to right, maintaining:
number: The current operand being assembled digit by digitoperator: The operator that precedesnumber(initially'+')stack: A list of signed terms that will be summed at the end
When we finish reading a number (detected by encountering an operator or reaching the end of the string), we apply the pending operator:
+: Pushnumberas a new positive term-: Push-numberas a new negative term*: Multiply the most recent term bynumber/: Divide the most recent term bynumber(truncating toward zero)
Multiplication and division immediately modify the top of the stack, implementing their higher precedence. Addition and subtraction simply add new terms that get summed later.
Why It Works
Any expression without parentheses can be viewed as: term₁ ± term₂ ± term₃ ...
Each term is a chain of numbers joined by * and /, evaluated left to right. By keeping a stack of signed terms and only modifying the top when we see * or /, we naturally respect precedence. The final sum collapses all the addition and subtraction operations.
For division, Python's // operator floors the result, but we need truncation toward zero. We handle this by dividing absolute values and applying the correct sign based on whether the operands have opposite signs.
Complexity
- Time: O(n) where n is the length of the string. Each character is processed once.
- Space: O(n) for the stack in the worst case (e.g.,
"1+1+1+..."). Could be optimized to O(1) by maintaining a running sum and last term instead of a stack.
Solution
def evaluate_expression(s: str) -> int:
stack = []
number = 0
operator = '+'
def apply(op, value):
if op == '+':
stack.append(value)
elif op == '-':
stack.append(-value)
elif op == '*':
stack[-1] *= value
else: # '/'
quotient = abs(stack[-1]) // abs(value)
if (stack[-1] < 0) != (value < 0):
quotient = -quotient
stack[-1] = quotient
for i, ch in enumerate(s):
if ch.isdigit():
number = number * 10 + ord(ch) - ord('0')
if (not ch.isdigit() and ch != ' ') or i == len(s) - 1:
apply(operator, number)
operator = ch
number = 0
return sum(stack)