Evaluate a Spaced Arithmetic String Without Parentheses
Stacks & QueuesAuto-graded · 28 test casesLast 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
*and/bind more tightly than+and-.- Operators of the same precedence level are applied from left to right.
/is integer division that truncates toward zero. For example,7/2is3, 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) <= 100000expressioncontains 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.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Any expression without parentheses is a sum of signed terms, and each term is a chain of * and / operations. For instance, 14-3/2+2*5 is the sum of +14, -(3/2) and +(2*5).
A stack solution would push signed numbers for +/- and, for *//, combine the top of the stack with the new number. Only the top is ever modified, so the stack can be replaced by two variables:
done_sum: the sum of all terms that are already closed.open_term: the current term, which a following*or/may still change.
While scanning left to right we also keep:
number: the integer being read, built vianumber = number * 10 + digit.pending_op: the operator that appeared beforenumber, initially+.
When we reach an operator (or the end of input), number is complete, so we apply pending_op:
pending_op | Action |
|---|---|
+ | add open_term to done_sum; open_term = number |
- | add open_term to done_sum; open_term = -number |
* | open_term *= number |
/ | open_term = truncated quotient of open_term / number |
Then we set pending_op to the new operator and reset number. Appending a + sentinel to the input makes the last number get flushed by the same code path. Spaces are skipped. The answer is done_sum + open_term.
Why it is correct
- A
+or-closes the current term. No later operator can alter a closed term, which is exactly what gives*and/higher precedence. *and/fold intoopen_termin reading order, which gives left-to-right evaluation inside a term, e.g.100/10*3 = (100/10)*3.- Subtraction is stored as a negative term, so a following
/acts on the signed value. Since truncation toward zero is symmetric,-(b/c)equals(-b)/cunder this rule. - Python's
//floors, so for the division step we divide absolute values and reapply the sign, giving true truncation toward zero.
Complexity
- Time:
O(n), one pass with constant work per character. - Space:
O(1)extra, apart from the one-character sentinel copy of the string.
Reference solution
def evaluate_expression(expression: str) -> int:
done_sum = 0 # sum of all closed additive terms
open_term = 0 # the term still open to * and /
number = 0 # number currently being read
pending_op = '+' # operator that precedes `number`
# A trailing '+' acts as a sentinel that flushes the last number.
for ch in expression + '+':
if ch.isdigit():
number = number * 10 + int(ch)
elif ch == ' ':
continue
else:
if pending_op == '+':
done_sum += open_term
open_term = number
elif pending_op == '-':
done_sum += open_term
open_term = -number
elif pending_op == '*':
open_term *= number
else: # '/'
quotient = abs(open_term) // number
open_term = quotient if open_term >= 0 else -quotient
pending_op = ch
number = 0
return done_sum + open_term