Basic Calculator II solution explained
Basic Calculator II asks you to evaluate a string such as "7 + 3*4 - 10/3" containing non-negative integers, the four operators and spaces, with multiplication and division done before addition and subtraction and division truncating toward zero. Read the string once, keeping the operator that came before the current number: push the number (or its negative) for + and -, and combine it with the top of a stack for * and /. Summing the stack gives the answer in O(n) time, and keeping only the last term brings space down to O(1).
By Evin JohnPublished 8 min read
Restating the problem
You get a valid arithmetic expression as a string. It contains non-negative whole numbers, the operators +, -, * and /, and any number of spaces. There are no brackets and no negative numbers written directly. Evaluate it with the usual precedence (multiply and divide first, left to right, then add and subtract) and return the integer result. Integer division drops the fractional part, rounding toward zero. You may not call a built-in expression evaluator.
"7 + 3*4 - 10/3" -> 16 (7 + 12 - 3)
"14/3*2" -> 8 (left to right: 4, then 8)
"2-9/2" -> -2 (9/2 is 4)
" 42 " -> 42
"0*5 + 1" -> 1Before coding, ask about integer size (can results overflow a 32-bit int?) and whether division by zero can appear. The usual answer is that inputs are valid and fit in ordinary integers, but asking shows you thought about it.
What it tests
The question checks whether you can turn precedence rules into a simple state machine instead of reaching for a full parser. It also tests careful string handling: numbers with several digits, spaces between anything, and the final number that has no operator after it. Interviewers often follow up with the constant-space version or with parentheses.
Straightforward: tokens, then two passes
The most readable approach splits the work. First turn the string into a list of numbers and operators. Then walk it once to apply every * and / to the number before it, producing a shorter list of terms joined by + and -. A second walk adds and subtracts those terms. It is linear, but it builds two intermediate lists and is longer to write under pressure.
def calculate_two_pass(s):
tokens, num = [], 0
for ch in s:
if ch.isdigit():
num = num * 10 + int(ch)
elif ch in "+-*/":
tokens += [num, ch]
num = 0
tokens.append(num)
terms, ops = [tokens[0]], []
for i in range(1, len(tokens), 2):
op, val = tokens[i], tokens[i + 1]
if op == "*":
terms[-1] *= val
elif op == "/":
terms[-1] //= val # terms here are never negative
else:
ops.append(op)
terms.append(val)
total = terms[0]
for op, val in zip(ops, terms[1:]):
total = total + val if op == "+" else total - val
return totalIn this version every term being multiplied or divided is non-negative, because signs are only applied in the last pass. That is why floor division is safe here. The one-pass version below folds the sign in early, and then it is not.
One pass with a stack of signed terms
Keep the operator that appeared before the number you are reading. When you reach the next operator (or the end of the string), you know what to do with that number. If its operator was +, push it. If it was -, push its negative. If it was * or /, pop the last term, combine it with the number, and push the result. Additions and subtractions wait on the stack until the end, which is exactly how precedence works.
def calculate(s):
stack, num, op = [], 0, "+"
for ch in s + "+":
if ch == " ":
continue
if ch.isdigit():
num = num * 10 + int(ch)
continue
if op == "+":
stack.append(num)
elif op == "-":
stack.append(-num)
elif op == "*":
stack.append(stack.pop() * num)
else:
top = stack.pop()
q = abs(top) // num
stack.append(q if top >= 0 else -q) # truncate toward zero
op, num = ch, 0
return sum(stack)The division line matters. In "2-9/2" the stack holds -9 when the / arrives. Python's -9 // 2 is -5 because it floors, but the problem wants -4, so divide the absolute value and put the sign back. Converting through floating point, as in int(top / num), also works for small values but can lose precision on very large ones.
function calculate(s) {
let total = 0;
let last = 0;
let num = 0;
let op = "+";
for (const ch of s + "+") {
if (ch === " ") continue;
if (ch >= "0" && ch <= "9") {
num = num * 10 + (ch.charCodeAt(0) - 48);
continue;
}
if (op === "+" || op === "-") {
total += last;
last = op === "+" ? num : -num;
} else if (op === "*") {
last *= num;
} else {
last = Math.trunc(last / num);
}
op = ch;
num = 0;
}
return total + last;
}Only the top of the stack is ever touched by * and /, and everything below it is just waiting to be added. So you can keep a running total plus the last term: when a new + or - term starts, add the last term to the total and start a new one. Math.trunc rounds toward zero, which is the rule the problem asks for, and it is exact as long as values stay within the range JavaScript numbers hold exactly.
Tracing "7 + 3*4 - 10/3"
| Number just read | Operator before it | Action | Stack |
|---|---|---|---|
| 7 | + | push 7 | 7 |
| 3 | + | push 3 | 7, 3 |
| 4 | * | pop 3, push 12 | 7, 12 |
| 10 | - | push -10 | 7, 12, -10 |
| 3 | / | pop -10, push -3 | 7, 12, -3 |
| (end) | sum the stack | 16 |
Complexity
| Approach | Time | Extra space |
|---|---|---|
| Tokens, then two passes | O(n) | O(n) for tokens and terms |
| One pass, stack of terms | O(n) | O(n) in the worst case (all additions) |
| One pass, total plus last term | O(n) | O(1) |
Inputs that catch bugs
- A single number with spaces around it, like " 42 ".
- Several digits in a row, like "123*10": build the number before acting on it.
- Chains like "14/3*2": left to right, not right to left.
- A negative term divided, like "2-9/2": truncation, not floor.
- Spaces inside the expression but not inside numbers, like "3 * 4".
Common mistakes
- Processing a number when you read its digits instead of when the next operator arrives, which applies the wrong operator.
- Forgetting the last number. The sentinel "+" at the end, or a check for the final index, fixes it.
- Treating a space as an operator and flushing the number early.
- Using floor division on a negative term in Python, or plain / without truncation in JavaScript.
- Calling eval or a similar built-in, which most interviewers rule out at the start.
Variations
- With parentheses and only + and -: keep a stack of signs; each "(" pushes the sign in front of it.
- With parentheses and all four operators: recurse on each bracketed part with the same one-pass loop, or use two stacks for numbers and operators.
- Unary minus: treat a - at the start or after another operator as part of the number.
- Reverse Polish notation input: no precedence to manage; push numbers and apply each operator to the top two.
How to explain it out loud
Fictional example
- Candidate
- Multiplication and division bind tighter, so I cannot add a number until I know what follows. I will remember the operator before each number and decide when the next operator shows up.
- Candidate
- Plus and minus mean the number becomes its own term, so I push it with its sign. Times and divide mean it belongs to the previous term, so I pop and combine.
- Interviewer
- Do you need the whole stack?
- Candidate
- No, only the top changes. I can keep a total and a last term, which makes the space constant. One thing to watch is dividing a negative term: the rule is truncation toward zero, so in Python I divide the absolute value.
Related problems
Also in this batch: Score of Parentheses evaluates nested brackets with a stack, and Simplify Path parses a string into stack operations. Asteroid Collision shows the same pop-combine-push rhythm with a different rule.
Preparing with Natively
Calculator problems reward a clear spoken plan more than clever code. On Mac or Windows, Natively can read the expression rules from a screenshot while you practice, suggest the operator-before-the-number idea or the constant-space step, and keep a transcript of your answer, so you can see whether you raised truncation for negative terms or left it for the interviewer to find. The LeetCode helper page covers the practice setup.
Questions people ask
How do you solve Basic Calculator II?
Scan the string once and remember the operator before the current number. When the next operator or the end arrives, push the number for +, its negative for -, or combine it with the top of the stack for * and /. Sum the stack.
How do you handle operator precedence without a parser?
Additions and subtractions are delayed on the stack, while multiplications and divisions are applied immediately to the most recent term, which gives them higher precedence.
Can Basic Calculator II be solved in O(1) space?
Yes. Keep a running total and the last term. Multiply or divide the last term in place, and add it to the total when a new + or - term starts.
How should division work for negative terms?
Truncate toward zero. In Python divide the absolute value and restore the sign, since // floors; in JavaScript use Math.trunc.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
