Four-Operator Integer Expression Evaluator

Easy · Coding & Algorithms · Software Engineer · Onsite

Problem Statement

Given a string s encoding a valid infix arithmetic formula, evaluate the formula and return its integer value.

The formula follows these rules:

  • Allowed characters: Base-10 non-negative integers (which may span multiple digits), the four binary operators '+', '-', '*', and '/', and space characters ' ' (spaces carry no meaning and may appear anywhere).
  • Well-formed input: s never contains parentheses, malformed tokens, or division by zero.
  • Precedence and associativity: Multiplication '*' and division '/' take priority over addition '+' and subtraction '-'. Operators with equal priority evaluate strictly from left to right.
  • Truncating integer division: Division '/' discards any fractional remainder toward zero (for example, 7 / 2 evaluates to 3, and -7 / 2 evaluates to -3).
def calculate(s: str) -> int:

Examples

Example 1

Input: s = "6+4*3"
Output: 18

Walk-through: - Multiplication runs before addition: 4 * 3 = 12, then 6 + 12 = 18.

Example 2

Input: s = " 20 - 7 / 2 "
Output: 17

Walk-through: - Surrounding and internal spaces are ignored. 7 / 2 truncates toward zero to 3, so 20 - 3 = 17.

Example 3

Input: s = "48/6*2-5"
Output: 11

Walk-through: - '/' and '*' share top priority and run left to right: 48 / 6 = 8, 8 * 2 = 16, and finally 16 - 5 = 11.

Constraints

  • 1 <= len(s) <= 10^5
  • All intermediate and final values fit inside a 32-bit signed integer ([-2^31, 2^31 - 1]).
  • Target O(n) time complexity and O(1) (or O(n)) auxiliary space, where n = len(s).

Step-by-step walkthrough

  1. Understand the rules and tricky parts

    We receive a string s containing non-negative integers, the four binary operators +, -, *, /, and optional spaces, with no parentheses and no invalid syntax. We want to evaluate s and return its integer value in a single O(n) pass.

    Three arithmetic rules need special care:

    • Operator precedence: * and / bind tighter than + and -, so 6 + 4 * 3 means 6 + (4 * 3) = 18, not (6 + 4) * 3 = 30.
    • Left-to-right associativity: Operators at the same priority level run from left to right, so 48 / 6 * 2 means (48 / 6) * 2 = 16 and 8 / 2 / 2 means (8 / 2) / 2 = 2.
    • Division truncates toward zero: Any fractional remainder is discarded (7 / 2 -> 3 and -7 / 2 -> -3).
  2. Start from the stack mental model

    Because there are no parentheses, every + and - acts like a wall separating the expression into independent signed chunks (terms), where each chunk is a number or a chain of * and /:

    Expression:   20  -  7 / 2  +  4 * 3
    Signed terms: [+20]  [-7/2]    [+4*3]
    Values:        +20     -3       +12    -->  sum = 29
    

    A classic way to evaluate these chunks is with a stack of integers:

    • When the operator in front of current_num is +, push +current_num.
    • When the operator in front of current_num is -, push -current_num.
    • When the operator in front of current_num is * or /, pop the top of the stack, multiply or divide it by current_num, and push the updated value back.

    At the end, the answer is simply sum(stack). That already runs in O(n) time, though storing the stack uses up to O(n) extra memory.

  3. Shrink the stack to O(1) space

    Look closely at what the stack actually touches: * and / only ever modify the most recent element on top of the stack. Every older element buried deeper in the stack is completely finished and will never change again!

    Stack view:     [ +20,  -3,  |  +12 ]
                     \________/     \__/
                       total      last_term
                (already finished) (still open to * or /)
    

    So we can replace the entire stack with just two integers:

    • total: the running sum of all finished chunks.
    • last_term: the signed value of the single active chunk at the top.

    Whenever a + or - starts a brand-new chunk, last_term is finished, so we fold it into total (total += last_term) and set last_term to +current_num or -current_num. Whenever * or / arrives, we update last_term in place!

  4. Handle integer division toward zero safely

    Because last_term carries its sign (for example, last_term = -7 in 20 - 7 / 2), dividing last_term by current_num can divide a negative integer by a positive integer.

    In Python, floor division // rounds down toward minus infinity rather than toward zero:

    -7 // 2  == -4   (floors downward -- WRONG here: 20 + (-4) = 16)
    trunc_div(-7, 2) == -3   (truncates toward zero -- RIGHT: 20 + (-3) = 17)
    

    Writing int(a / b) truncates toward zero for small integers, but / converts integers to 64-bit floats first, which silently loses accuracy above 2^53. A tiny pure-integer helper divides abs(dividend) // abs(divisor) and restores the minus sign when the signs differ:

    def trunc_div(dividend: int, divisor: int) -> int:
        """Integer division that truncates toward zero without float precision loss."""
        quotient = abs(dividend) // abs(divisor)
        # Negate when signs differ so e.g. -7 / 2 becomes -3 instead of Python's -7 // 2 == -4.
        if (dividend < 0) != (divisor < 0):
            return -quotient
        return quotient
    
  5. Scan characters left to right with a sentinel flush

    As we scan s character by character:

    1. Spaces: Ignore ' ' right away so spaces between digits and operators never trigger an early flush.
    2. Digits: Build multi-digit numbers one digit at a time with current_num = current_num * 10 + int(ch).
    3. Operators (and end of string): Reaching an operator ch tells us current_num has ended. Notice which operator applies to current_num: it is prev_op, the operator we remembered before current_num started (initialized to '+' for the very first number), NOT ch (which belongs to the next number!). After applying prev_op, we save prev_op = ch and reset current_num = 0.

    To avoid duplicating the operator logic after the loop for the final number, we loop i up to len(s) inclusive and pretend s[len(s)] is a trailing '+' sentinel character. That virtual '+' flushes the final number into last_term, and returning total + last_term finishes the sum.

  6. Trace Example 2 step by step

    Let's trace s = " 20 - 7 / 2 " (len(s) = 12). Spaces at i = 0, 3, 5, 7, 9, 11 are skipped; digits accumulate into current_num. Here is the exact state each time an operator (or the virtual '+' at i = 12) is processed:

    i    ch    current_num  prev_op  Action executed                    total  last_term  next prev_op
    -    start 0            '+'      (initial state)                    0      0          '+'
    4    '-'   20           '+'      total += 0;  last_term = +20       0      20         '-'
    8    '/'   7            '-'      total += 20; last_term = -7        20     -7         '/'
    12   '+'   2            '/'      last_term = trunc_div(-7, 2) = -3  20     -3         '+'
    end                              return total + last_term = 20 + (-3) = 17
    

    Notice how at i = 11 (' '), skipping the trailing space preserves current_num = 2 and prev_op = '/' until i = 12 flushes them cleanly.

  7. Complete solution

    from typing import Any, Dict, List, Optional, Set, Tuple
    
    
    def trunc_div(dividend: int, divisor: int) -> int:
        """Integer division that truncates toward zero without float precision loss."""
        quotient = abs(dividend) // abs(divisor)
        # Negate when signs differ so e.g. -7 / 2 becomes -3 instead of Python's -7 // 2 == -4.
        if (dividend < 0) != (divisor < 0):
            return -quotient
        return quotient
    
    
    def calculate(s: str) -> int:
        # total: sum of completed '+' / '-' chunks that '*' or '/' can no longer modify
        total = 0
        # last_term: signed value of the active chunk, e.g. -7 while scanning "20 - 7 / 2"
        last_term = 0
        # prev_op: operator sitting directly in front of current_num (starts as virtual '+')
        prev_op = "+"
        # current_num: multi-digit non-negative integer currently being assembled
        current_num = 0
    
        # Loop one step past len(s) with a virtual '+' sentinel to flush the final number.
        for i in range(len(s) + 1):
            if i < len(s):
                ch = s[i]
            else:
                ch = "+"
    
            # Skip spaces early so "3 * 2" does not treat ' ' like an operator.
            if ch == " ":
                continue
    
            if ch.isdigit():
                current_num = current_num * 10 + int(ch)
                continue
    
            # ch is an operator, so current_num is complete; apply prev_op (the operator BEFORE current_num).
            if prev_op == "+":
                # '+' begins a new chunk, so fold the finished last_term into total.
                total += last_term
                last_term = current_num
            elif prev_op == "-":
                # '-' begins a new negative chunk, folding the finished last_term into total.
                total += last_term
                last_term = -current_num
            elif prev_op == "*":
                # '*' binds tighter than '+' and '-', so merge directly into last_term.
                last_term = last_term * current_num
            elif prev_op == "/":
                # '/' binds tighter too and truncates toward zero even when last_term is negative.
                last_term = trunc_div(last_term, current_num)
    
            prev_op = ch
            current_num = 0
    
        # Add the final active chunk into the running sum.
        return total + last_term
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Think of + and - as walls dividing an expression into separate line items on a receipt: 20 - 7 * 2 + 9 is really three signed items (+20, -7 * 2, and +9) added together. This rule reflects operator precedence (the convention that * and / bind tighter and are computed before + and -) as well as left-associative evaluation (operators of equal priority, such as / followed by * in 48 / 6 * 2, execute strictly from left to right). Because you do not know whether a number is followed by * or / until you scan past it, you hold the current item on a one-slot scratchpad (last_term) and only add it into the permanent total once the next + or - wall arrives.

Evaluating strictly from left to right fails immediately on 6 + 4 * 3 because it adds 6 + 4 first to get 30 instead of 18. Repeatedly scanning a token list to splice out each * or / one at a time takes O(n^2) shifts, and even the standard stack-of-terms method allocates O(n) extra memory that we do not actually need because * and / only ever touch the single most recent term.

We scan s once while remembering prev_op (the operator sitting right in front of the number currently being read) and end with a sentinel—a dummy '+' processed one index past the end of s so the last number goes through the exact same logic without string copying. For /, we use truncating toward zero (dropping the fractional part so -7 / 2 becomes -3), rather than Python's floor division // (which rounds down toward minus infinity so -7 // 2 becomes -4).

Walk through Example 2, " 20 - 7 / 2 ":

  1. Start with total = 0, last_term = 0, and prev_op = '+'.
  2. Skip spaces, read 20, and hit '-': apply prev_op = '+' (total stays 0, last_term becomes +20), and record prev_op = '-'.
  3. Read 7 and hit '/': apply prev_op = '-' (total becomes 0 + 20 = 20, last_term becomes -7), and record prev_op = '/'.
  4. Read 2, skip the trailing space, and hit the virtual '+' sentinel at the end: apply prev_op = '/', updating last_term = trunc_div(-7, 2) = -3.
  5. Return total + last_term = 20 + (-3) = 17.

Complexity

Let n be the length of the input string s.

  • Time: O(n). The loop runs n + 1 iterations, visiting each character of s once and performing O(1) digit accumulation or integer arithmetic at each step.
  • Space: O(1) extra space. We store only four scalar variables (total, last_term, prev_op, current_num) and index directly into s rather than allocating a token list, stack, or modified copy of s.

Edge cases

  • Single number with spaces or leading zeros ("42", " 0 ", "007"): No operator appears inside s; the virtual '+' sentinel flushes current_num into last_term and returns 42, 0, and 7.
  • Trailing spaces (" 20 - 7 / 2 "): Skipping spaces before the operator logic ensures trailing spaces do not erase current_num before the sentinel '+' flushes it.
  • Chained same-precedence operators ("8/2/2", "10-3-2", "48/6*2"): Updating last_term as each operator arrives evaluates left to right, producing 2, 5, and 16.
  • Division after subtraction ("1-7/2", "0-9/4*3"): last_term is negative (-7 and -9), and trunc_div truncates -7 / 2 to -3 and -9 / 4 to -2, giving -2 and -6.
  • 32-bit signed extremes ("0-2147483647-1", "1073741824*2-1"): Python integers have arbitrary precision; in fixed-width languages like C++ or Java, total, last_term, and current_num should use 64-bit long to avoid intermediate overflow.

Common mistakes

  • Using Python's // directly on signed terms: Because -7 // 2 == -4 instead of -3, " 20 - 7 / 2 " wrongly evaluates to 16 unless you truncate toward zero (or keep last_term unsigned with a separate sign variable).
  • Using int(a / b) for truncating division: Floating-point division / only has 53 bits of significand precision, so huge integers above 2^53 silently round before int(...) truncates; abs(a) // abs(b) stays exact in integer arithmetic.
  • Applying the newly arrived operator instead of prev_op: When '/' arrives after 7 in "20 - 7 / 2", 7 belongs to the '-' in front of it, while '/' must wait until 2 has been read.
  • Treating spaces as non-digit operators: Checking if not ch.isdigit(): without skipping ' ' first flushes current_num = 0 on spaces and overwrites prev_op with ' '.
  • Building s + "+" in memory: Concatenating a character copies the entire 100,000-character string (O(n) extra space), whereas looping to len(s) with an if i < len(s) check keeps space O(1).

Alternative approaches

  • Explicit stack of signed terms: Push +current_num on +, -current_num on -, and replace stack[-1] with stack[-1] * current_num or trunc_div(stack[-1], current_num) on * and /, returning sum(stack). This is easy to write in interviews and takes O(n) time, at the cost of O(n) space.
  • Keep term non-negative with a separate sign (+1 or -1): Because input numbers are non-negative and there are no parentheses, keeping the +1/-1 sign separate from term ensures term >= 0 everywhere so plain term // current_num matches truncation toward zero, at the cost of one extra state variable.

Follow-up questions

  • How would you extend the evaluator to handle nested parentheses '(' and ')' while keeping O(n) runtime? A parenthesized sub-expression acts just like a single number whose value is computed first. Whenever you encounter '(', push the outer (total, last_term, prev_op) state onto a stack and reset those three variables to (0, 0, '+') for the inner expression; when you hit ')', finish the inner expression into current_num = total + last_term and pop the outer (total, last_term, prev_op) back so the outer prev_op applies to current_num naturally in O(n) time. Because a parenthesized result like (1 - 8) can be negative, trunc_div continues to handle (1 - 8) / 2 = -3 without any changes.
  • What adjustments are needed if unary '+' and '-' signs can precede numbers, such as '-6 * 2' or '8 * -3'? Track a boolean expecting_number = True (true at the start of the string and right after any binary operator) plus a num_sign = 1 multiplier for the upcoming number. If + or - arrives while expecting_number is true, flip num_sign instead of flushing a term; once digits finish, multiply current_num by num_sign before applying prev_op.
  • If untrusted user input could contain syntax errors or division by zero, how would you detect and report them cleanly? Track has_digit alongside current_num so you can verify that every operator is preceded by at least one digit, forbid spaces between two digits (such as "1 2"), and ensure the string ends after a number rather than a trailing operator. Inside the '/' branch, check if current_num == 0: and raise a clear ZeroDivisionError (or ValueError with the character index i) before calling trunc_div.

Follow-up questions

Similar questions

More Rokt interview questions

All 1 Rokt questions →