KatInterview

Evaluate Arithmetic Expression with Operator Precedence

Stacks & QueuesAuto-graded · 25 test cases
MediumAuto-gradedStacks & Queuesstackexpression-parsingoperator-precedence

Last updated

Tests implementation of expression evaluation using stacks to handle operator precedence and parentheses correctly.

Write a function that takes an arithmetic expression as a string and computes its result. The expression contains non-negative integers and the operators +, -, *, /, along with parentheses ().

Your evaluator must respect standard mathematical rules:

  • Multiplication and division bind more tightly than addition and subtraction
  • Operators of equal precedence associate left-to-right (so 8 - 3 - 2 equals 3, not 7)
  • Parentheses override the default precedence
  • Division truncates toward zero (so 7 / 2 gives 3, and (1 - 6) / 2 gives -2)

The input is guaranteed to be a valid expression with no division by zero. Whitespace may appear anywhere and should be ignored.

Constraints

  • 1 <= len(s) <= 10000
  • All integer operands are non-negative
  • The expression is well-formed and contains no division by zero
  • The result fits in a 32-bit signed integer

Examples

Example 1

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

Output: 7

Example 2

Input: evaluate_expression('(3 + 5) / 2')

Output: 4

Example 3

Input: evaluate_expression('12 + 3 * (4 - 2)')

Output: 18

Hints

Hint 1

Use two stacks: one for numbers and one for operators. Parentheses act as precedence barriers.

Hint 2

Before pushing a new operator, pop and apply all operators with greater or equal precedence to maintain left associativity.

Hint 3

For division with negative intermediates, divide the absolute values and then restore the correct sign to truncate toward zero.