KatInterview

Compute Arithmetic Expression with Operator Precedence

Stacks & QueuesAuto-graded · 24 test cases
MediumAuto-gradedStacks & Queuesstacksexpression-parsingoperator-precedence

Last updated

Tests parsing and evaluating mathematical expressions with proper operator precedence and parentheses using stack-based techniques.

Problem Statement

You are given a string expr representing a valid arithmetic expression. Your task is to compute and return the integer result of evaluating this expression.

The expression may contain:

  • Non-negative integers (including multi-digit numbers)
  • Binary operators: +, -, *, /
  • Parentheses: ( and )
  • Whitespace characters (which should be ignored)

Evaluation rules:

  • Multiplication (*) and division (/) have higher precedence than addition (+) and subtraction (-)
  • Operators with the same precedence are evaluated left-to-right (for example, 8-3-2 equals (8-3)-2 = 3, not 8-(3-2) = 7)
  • Parentheses override normal precedence and can be nested
  • Division performs integer division truncating toward zero:
    • 7 / 2 = 3 (positive result)
    • -7 / 2 = -3 (negative result truncates toward zero, not floor division which would give -4)
    • When dividing values with different signs, compute abs(a) / abs(b) and negate the result
  • The expression is always valid with balanced parentheses and no syntax errors
  • There are no unary operators (no standalone negative signs like -5)

Constraints

  • 1 <= expr.length <= 3 * 10^5
  • expr consists only of digits 0-9, operators +, -, *, /, parentheses (, ), and spaces
  • All intermediate results fit within a 32-bit signed integer
  • The expression is guaranteed to be valid

Examples

Example 1

Input: compute_expression('3+2*2')

Output: 7

Example 2

Input: compute_expression('(1+(4+5+2)-3)+(6+8)')

Output: 23

Example 3

Input: compute_expression('12 / 5 + 7 * (3 - 1)')

Output: 16

Example 4

Input: compute_expression('((20-7)/3)+2*4')

Output: 12

Hints

Hint 1

Consider using two stacks: one for numeric values and another for operators and parentheses to handle precedence correctly.

Hint 2

When you encounter an operator, think about which pending operators must be executed first based on precedence rules.

Hint 3

Be careful with division - Python's // operator floors the result, but you need truncation toward zero. For negative results, this makes a difference.