KatInterview

Evaluate Arithmetic String Without Parentheses

StringsAuto-graded · 28 test cases
MediumAuto-gradedStringsstringsparsingstacks-queues

Last updated

Parse and compute a non-negative integer arithmetic string with basic binary operators while preserving standard precedence and left-to-right evaluation.

Write a function that parses and evaluates a math expression string without using any built-in eval or standard library code execution facilities.

The string represents a mathematical expression containing non-negative integers, standard binary operators (+, -, *, /), and optional spaces.

Evaluation must adhere to the following rules:

  • Operators * and / have equal precedence, which is strictly higher than + and -.
  • Operators with equal precedence evaluate from left to right.
  • The division operator / represents integer division that truncates fractional results toward zero (for example, 7 / 2 = 3 and -7 / 2 = -3).
  • The expression will not contain parentheses or explicit unary sign operators (e.g., -5 at the start of a term).
  • Standard white space can appear anywhere outside of multi-digit numbers.
  • No division by zero will occur in the input.

Constraints

  • 1 <= len(s) <= 3 * 10^5
  • s consists only of digits, '+', '-', '*', '/', and ' '.
  • s is a valid arithmetic expression.
  • Each individual number in s is in the range [0, 2^31 - 1].
  • All intermediate calculations and the final output are guaranteed to fit within a signed 32-bit integer [-2^31, 2^31 - 1].

Examples

Example 1

Input: evaluate_expression('14 - 3*4 / 5 + 2')

Output: 14

Example 2

Input: evaluate_expression(' 7 / 2 * 3 ')

Output: 9

Example 3

Input: evaluate_expression('1-2-3')

Output: -4

Hints

Hint 1

Because multiplication and division have higher precedence, you can think of the entire expression as a series of additive terms, where each term is a sub-chain of multiplications and divisions.

Hint 2

Consider using a single pass with state variables (or a stack) to track the current term and overall accumulated sum.

Hint 3

Be careful with division truncation in Python! Python's `//` operator performs floor division toward negative infinity (e.g., `-7 // 2 = -4`), but the task requires truncation toward zero (`-3`).