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^5
  • s contains 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

  1. Understand the expression rules

    We receive a string s (up to 3 * 10^5 characters) containing non-negative integers, the four operators +, -, *, /, and optional spaces, and must return its integer value without calling eval().

    Three arithmetic rules govern every evaluation:

    • Multi-digit numbers and spaces: " 12 + 3 " contains the integers 12 and 3; 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, so 10 - 2 - 3 = (10 - 2) - 3 = 5 and 14 / 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 / 2 truncates to 4, giving 2 - 4 = -2.
  2. Why repeated token splicing is too slow

    A literal two-pass simulation first splits s into 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 length 3 * 10^5, roughly 1.5 * 10^5 splices cause O(n^2) element moves (billions of operations). To finish well under a second, we must scan s in a single O(n) pass.

  3. 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 = 6
    

    We can maintain those terms in a stack (terms list) 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 apply pending_op as soon as the next operator (or the end of the string) tells us current_num is complete.

  4. Handle truncating division on negative terms

    Because - pushes -current_num onto terms before seeing whether / comes next, 2 - 9 / 2 pushes -9 and later divides -9 by 2.

    Be careful with Python's // operator! Python's // performs floor division (rounding down toward -infinity), so -9 // 2 evaluates to -5 instead of -4, which would turn 2 + (-9 // 2) into -3 instead 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 -9 by 2 yields -4 — the exact negated value of 9 / 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_quotient
    
  5. Combine each finished number into the stack

    Once current_num has been completely read, apply_pending_operator folds it into terms according to pending_op:

    • "+": push +current_num as a new term.
    • "-": push -current_num as a new term.
    • "*": pop the top term and push last_term * current_num.
    • "/": pop the top term and push divide_toward_zero(last_term, current_num).

    Notice terms.pop() is guaranteed never to fail on "*" or "/" because the very first number always uses the initial pending_op = "+", pushing at least one item onto terms first.

    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))
    
  6. Scan the string in one pass and trace Example 4

    Now we walk s character by character:

    1. If ch is a digit ("0" <= ch <= "9"), shift the existing digits left and append the new digit: current_num = current_num * 10 + int(ch).
    2. If ch is an operator (ch in "+-*/"), current_num is complete: call apply_pending_operator, update pending_op = ch, and reset current_num = 0.
    3. If ch is a space, skip it completely.

    After the loop finishes, the last number in s has not met a following operator yet, so we call apply_pending_operator one final time and sum terms. Flushing after the loop (instead of checking i == len(s) - 1 inside 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
    
  7. 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 the n characters exactly once, doing O(1) arithmetic or stack push/pop work per character, and then sum at most n // 2 + 1 terms in O(n) time.
  • Space: O(n) worst-case. An expression made purely of additions and subtractions like "1+1+1+...+1" stores roughly n // 2 signed integers in terms (see Alternative approaches to reduce this to O(1)).

Edge cases

  • Single integer ("85" or "0"): The loop reads all digits without meeting an operator, the post-loop flush pushes +85 onto terms, and sum returns 85.
  • 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"): -7 sits on the stack when / 2 runs; divide_toward_zero(-7, 2) yields -3 (not Python's floored -7 // 2 == -4), so * 3 produces -9 and 2 + (-9) = -7.
  • Quotients smaller than 1 ("3 / 5" -> 0, "1 - 1 / 2" -> 1): abs(dividend) // abs(divisor) cleanly returns 0, avoiding -0 sign 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"): Integer abs(a) // abs(b) stays exact for arbitrarily large integers without floating-point precision loss from int(a / b).

Common mistakes

  • Using last_term // current_num directly for division: Python's // floors toward -infinity, turning -9 // 2 into -5 instead of -4 whenever a subtracted term is divided.
  • Applying the newly seen operator instead of pending_op: When the scanner reaches * in "4+3*5", the number 3 just finished belongs to the + before it; * belongs to the next number not yet read.
  • Checking if i == len(s) - 1: inside an elif or forgetting trailing spaces: Putting end-of-string flushing inside an elif skips 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 of current_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 modify terms[-1], while all earlier entries in terms sit frozen waiting to be summed! Keeping just two integers — completed_sum and last_term — folds last_term into completed_sum whenever + or - starts a new term, solving the full + - * / problem in O(n) time and O(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_expr handles +/- calling parse_term, which handles *// calling parse_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 helper eval_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 calls current_num, i = eval_from(i + 1) to evaluate everything up to the matching ')'; when eval_from sees ')', it flushes its local pending_op and returns (sum(local_terms), i) so the caller's pending * or / immediately multiplies or divides that parenthesized result in O(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 like 1.5e-3 (taking care not to treat the - right after e/E as subtraction!), then parse the slice once with float(token_str) so repeated * 0.1 multiplications do not accumulate rounding drift. Replace divide_toward_zero with true floating-point division last_term / current_num (or decimal.Decimal if exact base-10 cents/financial arithmetic is required) and define division-by-zero handling (ZeroDivisionError vs math.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: keep total = 0, current_num = 0, and sign = 1 (+1 for '+', -1 for '-'), adding sign * current_num directly into total whenever an operator or the end of s is reached. Even with * and / included, adding just one integer last_term alongside completed_sum keeps peak extra space O(1) because only the latest signed term can ever be multiplied or divided.

Follow-up questions

Similar questions

More Docker interview questions

All 2 Docker questions →