Evaluate Arithmetic String Without Parentheses
StringsAuto-graded · 28 test casesLast 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 = 3and-7 / 2 = -3). - The expression will not contain parentheses or explicit unary sign operators (e.g.,
-5at 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^5sconsists only of digits,'+','-','*','/', and' '.sis a valid arithmetic expression.- Each individual number in
sis 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`).
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Without parentheses, the expression follows a simple structure: a sequence of terms connected by + or - operators. Each term itself consists of one or more numbers multiplied or divided sequentially from left to right.
We can compute the result in a single left-to-right pass without needing a full operator stack:
- Maintain
totalto store the sum of all fully evaluated terms. - Maintain
termfor the current sequence of multiplications/divisions. - Keep track of
sign(+1or-1) for the current term based on the preceding+or-. - Keep track of any
pendingoperator (*or/) waiting for its right operand.
When parsing:
- Digits: Read the full integer
x. Ifpendingis set, combinetermwithxusing multiplication or truncated division. Otherwise, start a new term withx. +or-: Close out the activetermby addingsign * termtototal. Updatesignfor the upcoming term and clearpending.*or/: Store the operator aspending.- Spaces: Ignore and skip past them.
After iterating through the string, add the final active term multiplied by sign to total.
Truncation Note in Python
In Python, integer division a // b rounds down toward $-\infty$. For positive numbers, this matches truncation towards zero. To ensure signed intermediate terms truncate correctly towards zero, compute abs(term) // val and restore the sign afterwards.
Complexity
- Time Complexity: $\mathcal{O}(N)$, where $N$ is the length of the string. Each character is processed a constant number of times.
- Space Complexity: $\mathcal{O}(1)$ auxiliary space beyond string slicing for number conversions.
Python Reference Solution
def evaluate_expression(s: str) -> int:
total = 0
term = 0
sign = 1
pending = None
i = 0
n = len(s)
def apply_op(cur_term: int, op: str, val: int) -> int:
if op == "*":
return cur_term * val
# Division truncates towards zero
res = abs(cur_term) // val
return res if cur_term >= 0 else -res
while i < n:
ch = s[i]
if ch.isdigit():
j = i
while j < n and s[j].isdigit():
j += 1
x = int(s[i:j])
i = j
if pending is None:
term = x
else:
term = apply_op(term, pending, x)
continue
if ch == "+" or ch == "-":
total += sign * term
sign = 1 if ch == "+" else -1
pending = None
elif ch == "*" or ch == "/":
pending = ch
i += 1
return total + sign * term