Basic Calculator II
Basic Calculator II is LeetCode 227 (Medium). Given a string s holding a valid expression, return its value without using a built-in evaluator such as eval().
- The expression has non-negative integers, the operators
+,-,*,/, and spaces. There are no brackets. - Integer division truncates toward zero, so
-3 / 2counts as-1. sis up to 3 · 10⁵ characters long, so the evaluation has to be one linear pass.
- 1 <= s.length <= 3 * 10⁵
- s consists of integers and operators ('+', '-', '*', '/') separated by some number of spaces.
- s represents a valid expression.
- All the integers in the expression are non-negative integers in the range [0, 2³¹ - 1].
- The answer is guaranteed to fit in a 32-bit integer.
Intuition
* and / bind tighter than + and -, so 2 + 3 * 4 is 14, not 20. Applying each operator the moment you read it gets that wrong.
Instead, read the expression as a sum of terms: 2 + 3 * 4 - 6 / 2 is 2, 12 and -3 added together. A * or / only ever changes the term being built, never an earlier one. So keep the terms on a stack:
+or-: the next number starts a new term, pushed asnumor-num.*or/: the next number merges into the top term straight away.
When the string ends, adding up the stack applies every + and - in one go.
Two levels of operator strength and no brackets: settle the strong operators as soon as both sides are known, and leave the weak ones as a list to add up at the end.
Approach
Before reading on, evaluate 14 - 3 / 2 by hand and note which number the / acted on and which number the - belongs to. Aim for one O(n) pass.
Two ways to solve it
Push each +/- term, merge * and / into the top one, sum at the end.
- Clear: every term is visible on the stack.
- Extends: add a saved-state stack and it handles brackets too.
Only the newest term can still change, so keep it in last and fold older terms into total.
- No stack: two integers instead of a list.
- Same rules:
*and/changelast;+and-add it tototaland start a new one.
Both are one O(n) pass. The stack version is easier to check by hand and is the shape that grows into a solution with brackets. The second one is the usual follow-up when an interviewer asks for O(1) space. The steps, code and live demo follow the stack; the O(1) code comes after the demo.
Keep the operator that came before the number
Start with op = '+' and build each number digit by digit. When the number is complete, the operator that applies to it is the one written before it, so op is stored and used one number later.
Finish a number at an operator or at the last character
Act when ch is one of + - * /, or when i is the last index. The last number has nothing after it, so the index check is what catches it. Spaces never trigger anything, because they are neither.
Push a new term for + and -
If op is +, push num; if it is -, push -num. Putting the sign inside the term means the final step is a plain sum, with no subtraction left to do.
Merge * and / into the top term
If op is * or /, pop the top term, combine it with num, and push the result. The top term is the one this number belongs to, because only + and - start new terms. Divide with truncation toward zero: int(a / b) in Python, plain / in C++ and Java.
Add up the stack
After the loop, sum(stack) is the answer: every product and quotient is already settled, and each remaining entry carries its own sign.
Code in Python, C++ and Java
Running total and last term
A * or / only ever changes the newest term, so the stack's older entries are never touched again. Keep the newest term in last and everything before it summed in total. When + or - starts a new term, the old last is final and moves into total.
Common pitfalls
Floor division on a negative term
stack.append(stack.pop() // num)
stack.append(int(stack.pop() / num))
Every input number is non-negative, but a - pushes a negative term, and / can then act on it. Python's // rounds down, so -3 // 2 is -2. "14 - 3 / 2" returns 12 instead of 13.
Acting only when an operator appears
if ch in "+-*/":
if ch in "+-*/" or i == len(s) - 1:
The last number is never followed by an operator, so it is never pushed or merged. "3+2*2" returns 5, because the final * 2 is lost.
Treating any non-digit as an operator
if not ch.isdigit() or i == len(s) - 1:
if ch in "+-*/" or i == len(s) - 1:
A space then ends the number and is stored as op, and the next operator sees op == ' ' and falls into the division branch. In " 3+5 / 2 " the space after 5 leaves num at 0, so the / divides by zero and crashes.
Edge cases
" 3+5 / 2 "The last character is a space, but the i == len(s) - 1 check still fires there, so the waiting / 2 is applied before the loop ends.
Input numbers go up to 2³¹ - 1, so 2147483647 * 2 / 2 overflows an int at the multiply. The C++ and Java versions keep terms in 64-bit integers and convert only the final sum.
Complexity
s. Each character is read once, and each term is pushed once and popped at most once per * or /. The stack holds one entry per + or - term.Basic Calculator II FAQ
How is the version with brackets different?
Basic Calculator has brackets but only + and -, so there is no precedence to handle, only nesting. Its stack saves the outer total and the sign in front of each (, and restores them at ). Here the stack holds terms instead. Basic Calculator III has both brackets and all four operators.
Is int(a / b) safe, given that it goes through a float?
For the values in this problem, yes: terms stay far below 2⁵³, where a float still holds every whole number and the quotient lands on the right side of each integer. Above 2⁵³ the float quotient can round up to the next whole number, so the fully exact form is a // b when a >= 0 and -(-a // b) when a < 0.