KatInterview

Compute Arithmetic Expression with Operator Precedence

Stacks & QueuesAuto-graded · 29 test cases
MediumAuto-gradedStacks & Queuesparsingoperator-precedencemath

Last 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 = 2 and -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.