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:
snever 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 / 2evaluates to3, and-7 / 2evaluates 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 andO(1)(orO(n)) auxiliary space, wheren = len(s).
Step-by-step walkthrough
Understand the rules and tricky parts
We receive a string
scontaining non-negative integers, the four binary operators+,-,*,/, and optional spaces, with no parentheses and no invalid syntax. We want to evaluatesand return its integer value in a singleO(n)pass.Three arithmetic rules need special care:
- Operator precedence:
*and/bind tighter than+and-, so6 + 4 * 3means6 + (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 * 2means(48 / 6) * 2 = 16and8 / 2 / 2means(8 / 2) / 2 = 2. - Division truncates toward zero: Any fractional remainder is discarded (
7 / 2 -> 3and-7 / 2 -> -3).
- Operator precedence:
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 = 29A classic way to evaluate these chunks is with a stack of integers:
- When the operator in front of
current_numis+, push+current_num. - When the operator in front of
current_numis-, push-current_num. - When the operator in front of
current_numis*or/, pop the top of the stack, multiply or divide it bycurrent_num, and push the updated value back.
At the end, the answer is simply
sum(stack). That already runs inO(n)time, though storing the stack uses up toO(n)extra memory.- When the operator in front of
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_termis finished, so we fold it intototal(total += last_term) and setlast_termto+current_numor-current_num. Whenever*or/arrives, we updatelast_termin place!Handle integer division toward zero safely
Because
last_termcarries its sign (for example,last_term = -7in20 - 7 / 2), dividinglast_termbycurrent_numcan 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 above2^53. A tiny pure-integer helper dividesabs(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 quotientScan characters left to right with a sentinel flush
As we scan
scharacter by character:- Spaces: Ignore
' 'right away so spaces between digits and operators never trigger an early flush. - Digits: Build multi-digit numbers one digit at a time with
current_num = current_num * 10 + int(ch). - Operators (and end of string): Reaching an operator
chtells uscurrent_numhas ended. Notice which operator applies tocurrent_num: it isprev_op, the operator we remembered beforecurrent_numstarted (initialized to'+'for the very first number), NOTch(which belongs to the next number!). After applyingprev_op, we saveprev_op = chand resetcurrent_num = 0.
To avoid duplicating the operator logic after the loop for the final number, we loop
iup tolen(s)inclusive and pretends[len(s)]is a trailing'+'sentinel character. That virtual'+'flushes the final number intolast_term, and returningtotal + last_termfinishes the sum.- Spaces: Ignore
Trace Example 2 step by step
Let's trace
s = " 20 - 7 / 2 "(len(s) = 12). Spaces ati = 0, 3, 5, 7, 9, 11are skipped; digits accumulate intocurrent_num. Here is the exact state each time an operator (or the virtual'+'ati = 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) = 17Notice how at
i = 11(' '), skipping the trailing space preservescurrent_num = 2andprev_op = '/'untili = 12flushes them cleanly.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 ":
- Start with
total = 0,last_term = 0, andprev_op = '+'. - Skip spaces, read
20, and hit'-': applyprev_op = '+'(totalstays0,last_termbecomes+20), and recordprev_op = '-'. - Read
7and hit'/': applyprev_op = '-'(totalbecomes0 + 20 = 20,last_termbecomes-7), and recordprev_op = '/'. - Read
2, skip the trailing space, and hit the virtual'+'sentinel at the end: applyprev_op = '/', updatinglast_term = trunc_div(-7, 2) = -3. - Return
total + last_term = 20 + (-3) = 17.
Complexity
Let n be the length of the input string s.
- Time:
O(n). The loop runsn + 1iterations, visiting each character ofsonce and performingO(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 intosrather than allocating a token list, stack, or modified copy ofs.
Edge cases
- Single number with spaces or leading zeros (
"42"," 0 ","007"): No operator appears insides; the virtual'+'sentinel flushescurrent_numintolast_termand returns42,0, and7. - Trailing spaces (
" 20 - 7 / 2 "): Skipping spaces before the operator logic ensures trailing spaces do not erasecurrent_numbefore the sentinel'+'flushes it. - Chained same-precedence operators (
"8/2/2","10-3-2","48/6*2"): Updatinglast_termas each operator arrives evaluates left to right, producing2,5, and16. - Division after subtraction (
"1-7/2","0-9/4*3"):last_termis negative (-7and-9), andtrunc_divtruncates-7 / 2to-3and-9 / 4to-2, giving-2and-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, andcurrent_numshould use 64-bitlongto avoid intermediate overflow.
Common mistakes
- Using Python's
//directly on signed terms: Because-7 // 2 == -4instead of-3," 20 - 7 / 2 "wrongly evaluates to16unless you truncate toward zero (or keeplast_termunsigned 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 above2^53silently round beforeint(...)truncates;abs(a) // abs(b)stays exact in integer arithmetic. - Applying the newly arrived operator instead of
prev_op: When'/'arrives after7in"20 - 7 / 2",7belongs to the'-'in front of it, while'/'must wait until2has been read. - Treating spaces as non-digit operators: Checking
if not ch.isdigit():without skipping' 'first flushescurrent_num = 0on spaces and overwritesprev_opwith' '. - Building
s + "+"in memory: Concatenating a character copies the entire100,000-character string (O(n)extra space), whereas looping tolen(s)with anif i < len(s)check keeps spaceO(1).
Alternative approaches
- Explicit stack of signed terms: Push
+current_numon+,-current_numon-, and replacestack[-1]withstack[-1] * current_numortrunc_div(stack[-1], current_num)on*and/, returningsum(stack). This is easy to write in interviews and takesO(n)time, at the cost ofO(n)space. - Keep
termnon-negative with a separatesign(+1or-1): Because input numbers are non-negative and there are no parentheses, keeping the+1/-1sign separate fromtermensuresterm >= 0everywhere so plainterm // current_nummatches 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 intocurrent_num = total + last_termand pop the outer(total, last_term, prev_op)back so the outerprev_opapplies tocurrent_numnaturally inO(n)time. Because a parenthesized result like(1 - 8)can be negative,trunc_divcontinues to handle(1 - 8) / 2 = -3without 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 anum_sign = 1multiplier for the upcoming number. If+or-arrives whileexpecting_numberis true, flipnum_signinstead of flushing a term; once digits finish, multiplycurrent_numbynum_signbefore applyingprev_op. - If untrusted user input could contain syntax errors or division by zero, how would you detect and report them cleanly? Track
has_digitalongsidecurrent_numso 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, checkif current_num == 0:and raise a clearZeroDivisionError(orValueErrorwith the character indexi) before callingtrunc_div.
Follow-up questions
- How would you extend the evaluator to handle nested parentheses '(' and ')' while keeping O(n) runtime?
- What adjustments are needed if unary '+' and '-' signs can precede numbers, such as '-6 * 2' or '8 * -3'?
- If untrusted user input could contain syntax errors or division by zero, how would you detect and report them cleanly?
Similar questions
- 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
- Increment Digit Array