Left-to-Right Calculator Using Only Scalar State
StringsAuto-graded · 22 test casesLast updated
Evaluate a no-parentheses arithmetic string with correct precedence and truncating division in one pass, using only a few scalar variables instead of a stack.
Left-to-Right Calculator Using Only Scalar State
You are given a string expr containing a well-formed arithmetic expression. It consists of non-negative integers, the operators +, -, *, /, and space characters. There are no parentheses and no unary signs.
Compute the value of the expression and return it as an integer.
Rules
*and/have higher precedence than+and-.- Operators of equal precedence are applied from left to right. For example,
8/2*3means(8/2)*3, which is12. - Division is integer division that truncates toward zero. So
7/2is3, and a negative intermediate value such as-7divided by2gives-3(not-4). - Operands can have several digits. Spaces may appear at the start, at the end, or between tokens, and carry no meaning.
- The expression is always valid and never divides by zero.
Implementation requirement
Solve it in a single left-to-right pass, in O(n) time and O(1) extra space. Do not use an explicit stack (or any list/collection that grows with the input), and do not use recursion. A handful of integer variables is all you should need.
Constraints
exprcontains only digits,+,-,*,/, and spaces.- The expression is valid: it contains at least one number, and operators sit between numbers.
- No division by zero occurs.
- All intermediate and final values fit comfortably in Python integers; compute exactly with integer arithmetic (avoid floating point).
Examples
Example 1
Input: calculate_no_stack('3+2*2')
Output: 7
Example 2
Input: calculate_no_stack(' 3/2 ')
Output: 1
Example 3
Input: calculate_no_stack(' 3+5 / 2 ')
Output: 5
Hints
Hint 1
Only the most recent additive term can still be changed by a following `*` or `/`. Everything before it is final, so you can keep a running total of finished terms plus one 'open' term.
Hint 2
Process a number only when you reach the next operator (or the end of the string), and apply the operator that came BEFORE that number. Reset the number being built after each operator, and make sure the last number is flushed too.
Hint 3
For `+` and `-`, add the open term into the total and start a new open term with the signed number. For `*` and `/`, update the open term in place. For division, divide absolute values and restore the sign to get truncation toward zero.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Without parentheses, a new operator can only affect the most recent additive term. Everything before it is already final. So instead of a stack, we keep four integers:
total: the sum of all additive terms that are finished.open_term: the current signed term, which may still be multiplied or divided.number: the operand currently being read digit by digit.pending_op: the operator that appeared just beforenumber(initially+).
We scan the characters from left to right:
- A space is skipped.
- A digit extends the operand:
number = number * 10 + digit. - An operator means
numberis complete. We applypending_opto it, then record the new operator and resetnumberto 0.
Applying an operator to a completed operand value:
+: addopen_termintototal, then start a new open term equal tovalue.-: addopen_termintototal, then start a new open term equal to-value.*:open_term *= value./: divide the absolute value ofopen_termbyvalue, then restore the sign. This truncates toward zero, unlike Python's//, which floors.
The last operand has no operator after it, so we iterate over expr + '+'; the sentinel + flushes it. The answer is total + open_term.
Why it is correct
After each application, the value of the expression read so far equals total + open_term, where open_term is the signed value of the current run of * and / operations.
- A
+or-closes the current run, since nothing later can bind more tightly to it. Moving it intototalis safe. - A
*or/extends the run, and applying it immediately preserves left-to-right order. - Storing the sign inside
open_termmakesa - b*cbehave asa + (-b)*c. For truncating division,(-b)/cequals-(b/c), so this stays consistent.
Using integer arithmetic only avoids floating-point precision issues.
Complexity
- Time: O(n), one pass with constant work per character.
- Space: O(1) extra state (four integers). The
expr + '+'copy can be avoided by looping over indices and treating the indexlen(expr)as the sentinel, with no change to the logic.
Reference solution
def calculate_no_stack(expr: str) -> int:
total = 0 # sum of finalized additive terms
open_term = 0 # current signed term, still affected by * and /
number = 0 # operand currently being read
pending_op = '+' # operator that precedes `number`
def apply(op, value):
nonlocal total, open_term
if op == '+':
total += open_term
open_term = value
elif op == '-':
total += open_term
open_term = -value
elif op == '*':
open_term *= value
else: # '/', truncate toward zero
q = abs(open_term) // value
if open_term < 0:
q = -q
open_term = q
for ch in expr + '+': # trailing sentinel flushes the last operand
if ch == ' ':
continue
if '0' <= ch <= '9':
number = number * 10 + ord(ch) - ord('0')
else:
apply(pending_op, number)
pending_op = ch
number = 0
return total + open_term