KatInterview

Compute an Arithmetic Expression Honoring Operator Precedence

Stacks & QueuesAuto-graded · 25 test cases
MediumAuto-gradedStacks & Queuesparsingoperator-precedencestack

Last 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^5
  • s consists of digits, '+', '-', '*', '/', and ' '
  • s represents 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.