Evaluate Basic Arithmetic Strings
Medium · Coding & Algorithms · Software Engineer · Technical Screen
Problem Statement
Write a parser and evaluator for basic integer arithmetic strings without relying on built-in dynamic code execution such as eval() or exec():
def calculate(s: str) -> int:
The input string s encodes a syntactically valid formula composed of non-negative base-10 integers, the four binary operators +, -, *, and /, plus optional space characters ' ' anywhere before, between, or after tokens.
Evaluate s according to standard arithmetic rules:
- Multiplication (
*) and division (/) take precedence over addition (+) and subtraction (-). - Operators sharing the same precedence tier associate from left to right.
- Integer division truncates toward zero — discarding any remainder so positive quotients round down (
9 / 4 -> 2) and negative quotients round up (-9 / 2 -> -4).
Return the final integer value of the formula.
Examples
Example 1
Input: s = "4+3*5"
Output: 19
Walk-through: Because * binds tighter than +, 3 * 5 = 15 is computed before adding 4, yielding 4 + 15 = 19.
Example 2
Input: s = " 9 / 4 "
Output: 2
Walk-through: Leading, interior, and trailing spaces are ignored, and 9 / 4 = 2.25 drops its fractional part to become 2.
Example 3
Input: s = " 10 + 14 / 3 * 2 "
Output: 18
Walk-through: / and * share equal precedence and run left to right: 14 / 3 truncates to 4, 4 * 2 gives 8, and 10 + 8 = 18.
Example 4
Input: s = "2 - 9 / 2"
Output: -2
Walk-through: 9 / 2 truncates toward zero to 4, and subtracting from 2 produces 2 - 4 = -2.
Constraints
1 <= len(s) <= 3 * 10^5scontains only ASCII digits ('0'–'9'), operators ('+','-','*','/'), and spaces (' '), forming a valid expression with no division by zero.- Every input integer, intermediate result, and final return value fits in a signed 32-bit integer (
[-2^31, 2^31 - 1]).
Step-by-step walkthrough
Understand the expression rules
We receive a string
s(up to3 * 10^5characters) containing non-negative integers, the four operators+,-,*,/, and optional spaces, and must return its integer value without callingeval().Three arithmetic rules govern every evaluation:
- Multi-digit numbers and spaces:
" 12 + 3 "contains the integers12and3; spaces can appear anywhere and carry no meaning. - Operator precedence and left-to-right grouping:
*and/bind tighter than+and-. Operators at the same level run left to right, so10 - 2 - 3 = (10 - 2) - 3 = 5and14 / 3 * 2 = (14 / 3) * 2 = 8. - Truncation toward zero: Integer division drops the fractional part rather than rounding down to
-infinity. In"2 - 9 / 2",9 / 2truncates to4, giving2 - 4 = -2.
- Multi-digit numbers and spaces:
Why repeated token splicing is too slow
A literal two-pass simulation first splits
sinto a list of numbers and operators, then repeatedly finds the leftmost*or/, replaces[left, op, right]with[result], and finally repeats for+and-.That produces the right answer, but every splice into the middle of a Python list shifts all remaining elements left in
O(n)time. On"1*1*1*...*1"of length3 * 10^5, roughly1.5 * 10^5splices causeO(n^2)element moves (billions of operations). To finish well under a second, we must scansin a singleO(n)pass.Key idea: rewrite the expression as a sum of signed terms
Any expression without parentheses is simply a sum of independent signed terms, where
+starts a positive term,-starts a negative term, and chains of*and/stretch or shrink the current term:Original expression: 10 + 14 / 3 * 2 - 6 * 2 Signed terms: (+10) + (+14 / 3 * 2) + (-6 * 2) Resolved terms: [ 10, 8, -12 ] --> sum = 6We can maintain those terms in a stack (
termslist) as we read left to right! There is just one timing catch: when we encounter an operator like*, we have not yet read the number to its right. So we remember the operator sitting in front of the number we are currently reading (pending_op, initialized to an imaginary"+"before the very first number), and applypending_opas soon as the next operator (or the end of the string) tells uscurrent_numis complete.Handle truncating division on negative terms
Because
-pushes-current_numontotermsbefore seeing whether/comes next,2 - 9 / 2pushes-9and later divides-9by2.Be careful with Python's
//operator! Python's//performs floor division (rounding down toward-infinity), so-9 // 2evaluates to-5instead of-4, which would turn2 + (-9 // 2)into-3instead of-2.Instead, we divide
abs(dividend) // abs(divisor)and negate the result when the two inputs have opposite signs. Because truncation toward zero is symmetric (trunc(-a / b) == -trunc(a / b)), dividing-9by2yields-4— the exact negated value of9 / 2!def divide_toward_zero(dividend: int, divisor: int) -> int: """Integer division that drops the fractional part so -9 / 2 gives -4 (not -5).""" # Python's `//` floors toward -infinity (-9 // 2 == -5). Dividing magnitudes first # and restoring the sign afterward guarantees symmetric truncation toward zero. abs_quotient = abs(dividend) // abs(divisor) has_negative_sign = (dividend < 0) != (divisor < 0) if has_negative_sign: return -abs_quotient return abs_quotientCombine each finished number into the stack
Once
current_numhas been completely read,apply_pending_operatorfolds it intotermsaccording topending_op:"+": push+current_numas a new term."-": push-current_numas a new term."*": pop the top term and pushlast_term * current_num."/": pop the top term and pushdivide_toward_zero(last_term, current_num).
Notice
terms.pop()is guaranteed never to fail on"*"or"/"because the very first number always uses the initialpending_op = "+", pushing at least one item ontotermsfirst.def apply_pending_operator(terms: List[int], pending_op: str, current_num: int) -> None: """Fold `current_num` into `terms` using the operator that appeared right before it.""" # `+` and `-` start a brand-new signed term; `*` and `/` immediately update `terms[-1]` # because multiplication and division have higher precedence than addition/subtraction. if pending_op == "+": terms.append(current_num) elif pending_op == "-": terms.append(-current_num) elif pending_op == "*": last_term = terms.pop() terms.append(last_term * current_num) else: # pending_op == "/" last_term = terms.pop() terms.append(divide_toward_zero(last_term, current_num))Scan the string in one pass and trace Example 4
Now we walk
scharacter by character:- If
chis a digit ("0" <= ch <= "9"), shift the existing digits left and append the new digit:current_num = current_num * 10 + int(ch). - If
chis an operator (ch in "+-*/"),current_numis complete: callapply_pending_operator, updatepending_op = ch, and resetcurrent_num = 0. - If
chis a space, skip it completely.
After the loop finishes, the last number in
shas not met a following operator yet, so we callapply_pending_operatorone final time and sumterms. Flushing after the loop (instead of checkingi == len(s) - 1inside the loop) handles trailing spaces like" 9 / 4 "automatically!Trace on s = "2 - 9 / 2": Seen current_num pending_op Action triggered terms start 0 '+' - [] '2' 2 '+' digit -> build 2 [] ' ' 2 '+' space -> ignore [] '-' 0 '-' apply '+' to 2 -> push +2 [2] ' ' 0 '-' space -> ignore [2] '9' 9 '-' digit -> build 9 [2] '/' 0 '/' apply '-' to 9 -> push -9 [2, -9] '2' 2 '/' digit -> build 2 [2, -9] end - - apply '/' to 2 -> -9 / 2 = -4 [2, -4] Final sum: 2 + (-4) = -2- If
Complete solution
from typing import Any, Dict, List, Optional, Set, Tuple def divide_toward_zero(dividend: int, divisor: int) -> int: """Integer division that drops the fractional part so -9 / 2 gives -4 (not -5).""" # Python's `//` floors toward -infinity (-9 // 2 == -5). Dividing magnitudes first # and restoring the sign afterward guarantees symmetric truncation toward zero. abs_quotient = abs(dividend) // abs(divisor) has_negative_sign = (dividend < 0) != (divisor < 0) if has_negative_sign: return -abs_quotient return abs_quotient def apply_pending_operator(terms: List[int], pending_op: str, current_num: int) -> None: """Fold `current_num` into `terms` using the operator that appeared right before it.""" # `+` and `-` start a brand-new signed term; `*` and `/` immediately update `terms[-1]` # because multiplication and division have higher precedence than addition/subtraction. if pending_op == "+": terms.append(current_num) elif pending_op == "-": terms.append(-current_num) elif pending_op == "*": last_term = terms.pop() terms.append(last_term * current_num) else: # pending_op == "/" last_term = terms.pop() terms.append(divide_toward_zero(last_term, current_num)) def calculate(s: str) -> int: # terms: stack (list) of signed integer terms to sum at the end, e.g. [4, 15] for "4+3*5" terms: List[int] = [] # current_num: multi-digit integer currently being read left to right current_num = 0 # pending_op: operator sitting immediately to the left of `current_num` (imaginary '+' first) pending_op = "+" # Phase 1: Scan characters once; apply `pending_op` whenever an operator finishes `current_num`. for ch in s: if "0" <= ch <= "9": current_num = current_num * 10 + int(ch) elif ch in "+-*/": apply_pending_operator(terms, pending_op, current_num) pending_op = ch current_num = 0 # Spaces are ignored without touching `current_num` or `pending_op`. # Phase 2: Flush the final number (doing this after the loop safely handles trailing spaces). apply_pending_operator(terms, pending_op, current_num) # Phase 3: Every `*` and `/` is already resolved, so the answer is the sum of all signed terms. total = 0 for term in terms: total += term return total✅ Submit now — all tests should pass.
Intuition & how it works
Think of reading an itemized receipt from top to bottom where + and - start new line items, while * and / modify the line item you just wrote down (for example, 10 + 9 / 4 - 3 * 5 has three line items: +10, +9 / 4, and -3 * 5). You cannot add 9 into a permanent grand total the moment you see 9, because the very next operator might be / 4! Instead, we keep a notepad — a stack (a Last-In, First-Out list where inspecting or replacing the most recent item takes O(1) time) — of signed terms. Whenever + or - finishes a number, we push +number or -number onto the stack; whenever * or / finishes a number, we pop the last term, multiply or divide it immediately, and push the updated term back. Once the scan ends, all high-precedence * and / operations are already resolved, so we just sum the stack.
Why do simpler approaches break down? Evaluating strictly left to right with one running number ignores operator precedence (the rule that * and / bind tighter than + and -), turning 4 + 3 * 5 into (4 + 3) * 5 = 35 instead of 19. Conversely, splitting the string into a list of tokens and repeatedly splicing out each * or / shifts the remaining list on every step, taking O(n^2) time on a 300,000-character input.
Let's trace "4 + 3 * 5" and "2 - 9 / 2" (pending_op remembers the operator before the number being read, starting at "+"):
s = "4 + 3 * 5":
read 4, see '+' -> apply '+' to 4: terms = [4], pending_op = '+'
read 3, see '*' -> apply '+' to 3: terms = [4, 3], pending_op = '*'
read 5, end -> apply '*' to 5: terms = [4, 15] -> sum = 19
s = "2 - 9 / 2":
read 2, see '-' -> apply '+' to 2: terms = [2], pending_op = '-'
read 9, see '/' -> apply '-' to 9: terms = [2, -9], pending_op = '/'
read 2, end -> apply '/' to 2: divide_toward_zero(-9, 2) = -4 -> terms = [2, -4] -> sum = -2
Complexity
Let n be the number of characters in s.
- Time:
O(n). We inspect each of thencharacters exactly once, doingO(1)arithmetic or stack push/pop work per character, and then sum at mostn // 2 + 1terms inO(n)time. - Space:
O(n)worst-case. An expression made purely of additions and subtractions like"1+1+1+...+1"stores roughlyn // 2signed integers interms(see Alternative approaches to reduce this toO(1)).
Edge cases
- Single integer (
"85"or"0"): The loop reads all digits without meeting an operator, the post-loop flush pushes+85ontoterms, andsumreturns85. - Leading, trailing, and repeated spaces (
" 10 + 14 / 3 * 2 "): Spaces are completely ignored during the loop, and flushing after the loop ensures trailing spaces never skip or double-flush the final number. - Division after a minus sign (
"2 - 9 / 2"or"2 - 7 / 2 * 3"):-7sits on the stack when/ 2runs;divide_toward_zero(-7, 2)yields-3(not Python's floored-7 // 2 == -4), so* 3produces-9and2 + (-9) = -7. - Quotients smaller than
1("3 / 5"->0,"1 - 1 / 2"->1):abs(dividend) // abs(divisor)cleanly returns0, avoiding-0sign issues. - Chains of same-precedence operators (
"10 - 2 - 3"->5,"14 / 3 * 2"->8): Left-to-right scan naturally evaluates equal-precedence chains in reading order rather than right-to-left. - Large 32-bit integers (
"2147483647/7*7"): Integerabs(a) // abs(b)stays exact for arbitrarily large integers without floating-point precision loss fromint(a / b).
Common mistakes
- Using
last_term // current_numdirectly for division: Python's//floors toward-infinity, turning-9 // 2into-5instead of-4whenever a subtracted term is divided. - Applying the newly seen operator instead of
pending_op: When the scanner reaches*in"4+3*5", the number3just finished belongs to the+before it;*belongs to the next number not yet read. - Checking
if i == len(s) - 1:inside anelifor forgetting trailing spaces: Putting end-of-string flushing inside anelifskips flushing when the last character is a digit, and treating non-digits as operators treats" "as/! Flushing once unconditionally after the loop avoids both traps. - Parsing only single-digit numbers: Writing
current_num = int(ch)instead ofcurrent_num = current_num * 10 + int(ch)breaks multi-digit inputs like"85"or"100*20/3".
Alternative approaches
- Running sum +
last_term(O(1)extra space): Notice we only ever modifyterms[-1], while all earlier entries intermssit frozen waiting to be summed! Keeping just two integers —completed_sumandlast_term— foldslast_termintocompleted_sumwhenever+or-starts a new term, solving the full+ - * /problem inO(n)time andO(1)space. - Two-stack / Shunting-Yard algorithm: Dijkstra's Shunting-Yard algorithm keeps one stack of numbers and one stack of operators, popping operators of greater-or-equal precedence before pushing a new operator. It generalizes cleanly to parentheses and exponentiation (
^), though it takes more code when there are only two precedence tiers. - Recursive descent parser: A recursive descent parser writes one mutually recursive function per grammar level (
parse_exprhandles+/-callingparse_term, which handles*//callingparse_number). It is the standard compiler textbook design and extends effortlessly to unary operators, functions, and variables.
Follow-up questions
- *How would you extend the evaluator if nested parentheses such as "(4+3)5" were allowed? Treat every
(...)sub-expression as a single number computed by a recursive helpereval_from(index) -> (value, next_index)(or save(terms, pending_op)onto an explicit outer stack on'('to avoid recursion depth limits). When the scanner sees'(', it callscurrent_num, i = eval_from(i + 1)to evaluate everything up to the matching')'; wheneval_fromsees')', it flushes its localpending_opand returns(sum(local_terms), i)so the caller's pending*or/immediately multiplies or divides that parenthesized result inO(n)total time. - What adjustments are required to parse and evaluate decimal floating-point operands instead of integers? Extend the number reader to collect digits, a decimal point
., and optional scientific notation like1.5e-3(taking care not to treat the-right aftere/Eas subtraction!), then parse the slice once withfloat(token_str)so repeated* 0.1multiplications do not accumulate rounding drift. Replacedivide_toward_zerowith true floating-point divisionlast_term / current_num(ordecimal.Decimalif exact base-10 cents/financial arithmetic is required) and define division-by-zero handling (ZeroDivisionErrorvsmath.inf). - *How can you achieve O(1) auxiliary memory when the input contains only '+' and '-' (and even when '' and '/' remain)? Without
*and/, no future operator can ever alter a number after it is read, so we need no stack at all: keeptotal = 0,current_num = 0, andsign = 1(+1for'+',-1for'-'), addingsign * current_numdirectly intototalwhenever an operator or the end ofsis reached. Even with*and/included, adding just one integerlast_termalongsidecompleted_sumkeeps peak extra spaceO(1)because only the latest signed term can ever be multiplied or divided.
Follow-up questions
- How would you extend the evaluator if nested parentheses such as "(4+3)*5" were allowed?
- What adjustments are required to parse and evaluate decimal floating-point operands instead of integers?
- How can you achieve O(1) auxiliary memory when the input contains only '+' and '-' (and even when '*' and '/' remain)?
Similar questions
- Distributed Container Image Registry
- 2D Max Pooling with Source Coordinates
- Time-Limited Credit Ledger
- Grid Path Scoring with Streak Bonuses
- Place One Hub to Minimize Maximum Grid Distance
- Increment Fixed-Size Digit Array by One