Arithmetic String Calculator with Operator Precedence
Stacks & QueuesModel answerLast 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/2is3, and a negative intermediate such as-7/2is-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:
| Input | Output |
|---|---|
"3+2*2" | 7 |
" 3/2 " | 1 |
"14 - 3 / 2" | 13 |
"1-3/2" | 0 |
"8/3*3" | 6 |
"42" | 42 |
What to deliver:
- A working function.
- A short explanation of how you handle precedence and truncation.
- The time and space complexity of your approach.
- 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.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Key observation
With no parentheses, an expression is a sum of signed terms, where each term is a product/quotient chain:
14 - 3 / 2 + 4 * 5 * 2
= (+14) + (-(3 / 2)) + (+(4 * 5 * 2))
So no general parser is needed. A single left-to-right scan is enough if we resolve * and / inside the current term and only add a term to the total once a + or - closes it.
Stack version (a good first answer)
Keep the operator that preceded the number being read (start with +). When a number is complete:
+: pushnum-: push-num*: pop the top, pushtop * num/: pop the top, pushtrunc(top / num)
At the end, the answer is the sum of the stack. Time is O(n), space is O(n) in the worst case (for example 1+1+1+...).
O(1) space version
Only the top of the stack is ever modified, and everything beneath it is only summed. So replace the stack with two variables:
result: sum of terms that are already closed,last: the current term, with its sign applied.
| Preceding operator | Action when a number num completes |
|---|---|
+ | result += last; last = num |
- | result += last; last = -num |
* | last = last * num |
/ | last = trunc(last / num) |
The answer is result + last.
Why it is correct
- Precedence:
+and-close the current term, so*and/can only ever touchlast. Each multiplicative chain is fully resolved before joining the sum. - Left-to-right order: each operator is folded into
lastas soon as its right operand is read, soa / b * cis computed as(a / b) * c. - Subtraction: the sign goes into the term, so
1 - 3/2becomes1 + (-3/2). Since truncation toward zero satisfiestrunc(-x/y) = -trunc(x/y), the result equals1 - (3/2) = 0, as required. - First and last numbers: start with the previous operator as
+andlast = 0, so the first number is handled uniformly. Run the "apply operator" step also at the final index so the last number is flushed.
Truncating division in Python
Python's // floors, so -3 // 2 == -2, which is wrong here. int(a / b) goes through floating point and loses precision for values beyond 2^53. Use integer-only truncation:
q = abs(a) // abs(b)
return -q if (a < 0) != (b < 0) else q
Code
def calculate(s: str) -> int:
def div_trunc(a: int, b: int) -> int:
q = abs(a) // abs(b)
return -q if (a < 0) != (b < 0) else q
result = 0 # sum of closed terms
last = 0 # current term, sign included
num = 0 # number being parsed
op = '+' # operator preceding num
n = len(s)
for i, ch in enumerate(s):
if ch.isdigit():
num = num * 10 + (ord(ch) - ord('0'))
if ch in '+-*/' or i == n - 1:
if op == '+':
result += last
last = num
elif op == '-':
result += last
last = -num
elif op == '*':
last *= num
else:
last = div_trunc(last, num)
op = ch
num = 0
return result + last
Notes:
- The
i == n - 1check also fires when the last character is a space. This is still correct because spaces never resetnum. - After the final flush,
opmay be set to a digit or space. It is never used again, so this is harmless. - Parsing character by character avoids creating substrings on very long inputs.
Trace of "14-3/2"
| Event | result | last |
|---|---|---|
number 14 completes at - (op +) | 0 | 14 |
number 3 completes at / (op -) | 14 | -3 |
number 2 completes at end (op /) | 14 | -1 |
Answer: 14 + (-1) = 13.
Complexity
- Time: O(n). Each character is visited once, and numbers are built in the same pass. (With Python's arbitrary-precision integers, a single enormous number costs work proportional to its digit count; under a fixed-width assumption every operation is O(1).)
- Space: O(1) extra for the two-variable version; O(n) for the stack version.
Edge cases to test
- Spaces anywhere, including leading and trailing:
" 3 / 2 "gives1. - Multi-digit numbers:
"1000*20"gives20000. - A single number:
"42"gives42. - Negative intermediate with division:
"1-3/2"gives0,"0-7/2"gives-3. - Chained same-precedence operators:
"8/3*3"gives6, not8. - Very long input: one pass and no recursion, so no stack-overflow risk.
Common mistakes
- Forgetting to flush the last number, especially when the string ends with a space.
- Using
//orint(a / b)for division with negative intermediates or huge values. - Evaluating strictly left to right and ignoring precedence.
- Resetting
numon a space, which breaks numbers split by whitespace handling. - Rewriting the string in several passes instead of resolving terms structurally.
Follow-ups to be ready for
- Parentheses: recurse on
(and return the sub-result at the matching), or push(result, last, op)onto an explicit stack to avoid recursion depth limits. - Unary minus: treat a
-at the start or right after(or another operator as a sign on the next number. - Validation: detect malformed input and division by zero and raise clear errors.