KatInterview

Evaluate a Spaced Arithmetic String Without Parentheses

Stacks & QueuesAuto-graded · 28 test cases
MediumAuto-gradedStacks & Queuesparsingstringstack

Last updated

Evaluate an integer expression with +, -, *, / using standard precedence and truncating division, in a single pass over a string with arbitrary spacing.

Evaluate a Spaced Arithmetic String Without Parentheses

You are given a string expression that holds an arithmetic formula. Compute its value and return it as an integer.

Input format

The string consists only of:

  • non-negative decimal integers, which may have several digits,
  • the four operators +, -, *, /,
  • space characters, which carry no meaning and must be ignored.

The formula is always well formed: there are no parentheses, no unary signs, and no division by zero. Spaces may appear anywhere, including before, after, or inside a run of characters between tokens.

Evaluation rules

  1. * and / bind more tightly than + and -.
  2. Operators of the same precedence level are applied from left to right.
  3. / is integer division that truncates toward zero. For example, 7/2 is 3, and a negative quotient such as the one arising from the term -(7/2) is -3, not -4.

Return the final integer value.

Constraints

  • 1 <= len(expression) <= 100000
  • expression contains only digits, +, -, *, /, and spaces.
  • The expression is valid, and it contains at least one number.
  • No division by zero occurs.
  • The final result fits in a 32-bit signed integer.
  • A solution running in O(n) time is expected.

Examples

Example 1

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

Output: 7

Example 2

Input: evaluate_expression(' 14-3/2 ')

Output: 13

Example 3

Input: evaluate_expression('100/10*3+5')

Output: 35

Hints

Hint 1

Think of the formula as a sum of signed terms, where each term is a chain of multiplications and divisions. A + or - always closes the current term and opens a new one.

Hint 2

Read the string left to right, building each number digit by digit. When you hit an operator (or the end), apply the operator that came BEFORE the number you just finished.

Hint 3

Keep two running values: the total of finished terms and the current open term. For truncation toward zero in Python, divide the absolute values and then restore the sign, instead of using // directly on a negative number.