KatInterview

Arithmetic String Calculator with Operator Precedence

Stacks & QueuesModel answer
MediumModel answerStacks & Queuesparsingstackstring

Last updated

Compute the integer result of a string holding non-negative numbers, four operators and spaces, honoring precedence and truncating division, without eval and with linear time.

Write a function that takes a string representing an arithmetic expression and returns its integer value.

The string contains only:

  • non-negative integers (possibly several digits),
  • the operators +, -, *, /,
  • space characters, which may appear anywhere and should be ignored.

Rules:

  • * and / bind more tightly than + and -.
  • Operators with the same precedence are applied from left to right.
  • Division is integer division that truncates toward zero (so 7/2 is 3, and a negative intermediate such as -7/2 is -3).
  • There are no parentheses and no unary minus.
  • You may assume the expression is well formed and never divides by zero.
  • Do not use a built-in expression evaluator such as eval.
  • The input can be very long, so the solution must be efficient.

Examples:

InputOutput
"3+2*2"7
" 3/2 "1
"14 - 3 / 2"13
"1-3/2"0
"8/3*3"6
"42"42

What to deliver:

  1. A working function.
  2. A short explanation of how you handle precedence and truncation.
  3. The time and space complexity of your approach.
  4. A list of edge cases you would test.

Hints

Hint 1

Without parentheses, the whole expression is a sum of terms, and each term is a run of numbers joined by `*` and `/`. Think about how to resolve each term before adding it to the total.

Hint 2

Scan once, building each number digit by digit. When you finish a number, act on the operator that came before it: for `+` or `-` push a signed value, for `*` or `/` combine it with the most recent value.

Hint 3

Only the most recent term is ever modified, so the stack can be reduced to two variables: a running sum of finished terms and the current term. Be careful to flush the final number, and remember that Python's `//` floors rather than truncates for negatives.

Hint 4

Fold the sign into the term (store `-num` after a `-`). Because truncation toward zero is symmetric, `trunc(-a/b) == -trunc(a/b)`, so this does not change results.