Compute Arithmetic Expression with Operator Precedence
Stacks & QueuesAuto-graded · 29 test casesLast updated
Tests ability to parse and evaluate arithmetic expressions respecting operator precedence and left-to-right associativity without built-in eval.
Write a function that computes the result of an arithmetic expression given as a string. The expression contains non-negative integers and the operators +, -, *, /, with optional whitespace.
Follow standard operator precedence: * and / bind tighter than + and -. When operators have equal precedence, evaluate left to right. Division is integer division that truncates toward zero (not floor division).
Do not use eval() or equivalent library functions that directly evaluate expressions.
Input
expr: a string representing a valid arithmetic expression- Contains only digits
0-9, spaces, and operators+,-,*,/ - The expression is well-formed (no syntax errors, no parentheses)
- No division by zero will occur
Output
Return the integer result of evaluating the expression.
Constraints
1 <= len(expr) <= 300,000- All numbers in the expression are non-negative integers
- The final result and all intermediate values fit within a signed 32-bit integer
- Division truncates toward zero:
7 / 3 = 2and-7 / 3 = -2
Examples
Example 1
Input: compute_expression('3+2*2')
Output: 7
Example 2
Input: compute_expression(' 14-3/2 ')
Output: 13
Example 3
Input: compute_expression('0-7/3')
Output: -2
Hints
Hint 1
Think of the expression as a sum of terms, where each term is a chain of multiplications and divisions.
Hint 2
You can process the string in a single left-to-right pass, maintaining the running total and the current term being built.
Hint 3
Python's // operator floors toward negative infinity, not toward zero. For negative dividends, you need to handle the sign separately.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The core insight is that any expression without parentheses can be viewed as a sum of terms: term₁ ± term₂ ± term₃ ... where each term is a sequence of numbers connected by * and / operators.
We maintain three pieces of state during a single left-to-right scan:
running_total: accumulates the sum of all completed termscurrent_term: the value of the term currently being built (includes its sign)last_op: the operator that precedes the number we just parsed
When we encounter an operator (or reach the end), we apply the previous operator to the number we just read:
- For
+or-: the current term is complete, so we add it torunning_totaland start a new term with the appropriate sign - For
*or/: we continue building the current term by multiplying or dividing
We initialize last_op to '+' so the first number is treated uniformly. We also treat the end of the string as an implicit + operator, which flushes the last term without special-case code.
Correctness
Precedence: Multiplication and division only modify current_term, never running_total, ensuring these operations complete before addition/subtraction.
Associativity: Within a term, each * or / is applied immediately to the accumulated value, giving left-to-right evaluation. Across terms, subtraction is encoded as adding a negative term: a - b - c becomes a + (-b) + (-c), which equals (a - b) - c.
Truncation toward zero: Python's // operator floors toward negative infinity, so -7 // 3 = -3. To truncate toward zero instead, we divide the absolute values and restore the sign: abs(term) // num gives the magnitude, then we negate if term was negative.
Complexity
- Time: O(n) where n is the length of the expression. Each character is visited once, and digit parsing advances the index past the entire number.
- Space: O(1) auxiliary space. We use only a fixed number of variables. The number parsing creates a temporary string slice, but this is proportional to the number's length, not the total expression length.
Implementation
def compute_expression(expr: str) -> int:
running_total = 0
current_term = 0
current_num = 0
last_op = '+'
n = len(expr)
i = 0
while i <= n:
char = expr[i] if i < n else '+'
if '0' <= char <= '9':
j = i
while j < n and '0' <= expr[j] <= '9':
j += 1
current_num = int(expr[i:j])
i = j
continue
if char == ' ':
i += 1
continue
if last_op == '+':
running_total += current_term
current_term = current_num
elif last_op == '-':
running_total += current_term
current_term = -current_num
elif last_op == '*':
current_term = current_term * current_num
else:
quotient = abs(current_term) // current_num
current_term = quotient if current_term >= 0 else -quotient
last_op = char
current_num = 0
i += 1
return running_total + current_term