LeetCode #227 Medium

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 / 2 counts as -1.
  • s is up to 3 · 10⁵ characters long, so the evaluation has to be one linear pass.
Constraints
  • 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.
stackmathstrings
Open on LeetCode ↗
02

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 as num or -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.

How to spot this pattern

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.

03

Approach

Try it first

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.

1

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.

2

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.

3

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.

4

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.

5

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.

04

Code in Python, C++ and Java

▶1class Solution:
▶2 def calculate(self, s):
▶3 stack = []
▶4 num, op = 0, "+"
▶5 for i, ch in enumerate(s):
▶6 if ch.isdigit():
▶7 num = num * 10 + int(ch)
▶8 if ch in "+-*/" or i == len(s) - 1:
▶9 if op == "+":
▶10 stack.append(num)
▶11 elif op == "-":
▶12 stack.append(-num)
▶13 elif op == "*":
▶14 stack.append(stack.pop() * num)
▶15 else:
▶16 stack.append(int(stack.pop() / num))
▶17 op, num = ch, 0
▶18 return sum(stack)
expression3+2×2op before number+number3terms (stack, bottom → top)emptydigit 3 → number 3
op+
number3
termsnone
A digit starts a number. Nothing is pushed yet: more digits may follow, and the number is only finished by an operator or the end of the string.
expression3+2×2op before number+numberterms (stack, bottom → top)33 ends, op was + → push new term 3
op+
numbernone
terms3
The number 3 is finished. The operator before it was plus, so it starts a new term, pushed as 3. Earlier terms are left alone: a later × or ÷ can only touch this new one. Then plus becomes the operator for the next number.
expression3+2×2op before number+number2terms (stack, bottom → top)3digit 2 → number 2
op+
number2
terms3
A digit starts a number. Nothing is pushed yet: more digits may follow, and the number is only finished by an operator or the end of the string.
expression3+2×2op before number×numberterms (stack, bottom → top)3+22 ends, op was + → push new term 2
op*
numbernone
terms3, 2
The number 2 is finished. The operator before it was plus, so it starts a new term, pushed as 2. Earlier terms are left alone: a later × or ÷ can only touch this new one. Then times becomes the operator for the next number.
expression3+2×2op before number×number2terms (stack, bottom → top)3+2digit 2 → number 2
op*
number2
terms3, 2
A digit starts a number. Nothing is pushed yet: more digits may follow, and the number is only finished by an operator or the end of the string.
expression3+2×2op before number×numberterms (stack, bottom → top)3+4last index: 2 ends, op was × → top term 2 × 2 = 4
op*
numbernone
terms3, 4
This is the last character, so the number ends here even though no operator follows. The operator before 2 was times, which binds tighter than + and −. So pop the top term 2, multiply it by 2, and push 4 back.
expression3+2×2op before number×numberterms (stack, bottom → top)3+4=7add up the terms → answer 7
answer7
Every × and ÷ has already been folded into its term, and each term carries its own sign. Adding the terms 3, 4 gives 7.
05

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.

▶1class Solution:
▶2 def calculate(self, s):
▶3 total, last, num, op = 0, 0, 0, "+"
▶4 for i, ch in enumerate(s):
▶5 if ch.isdigit():
▶6 num = num * 10 + int(ch)
▶7 if ch in "+-*/" or i == len(s) - 1:
▶8 if op == "+":
▶9 total += last
▶10 last = num
▶11 elif op == "-":
▶12 total += last
▶13 last = -num
▶14 elif op == "*":
▶15 last *= num
▶16 else:
▶17 last = int(last / num)
▶18 op, num = ch, 0
▶19 return total + last
06

Common pitfalls

Floor division on a negative term

✗ Wrong
stack.append(stack.pop() // num)
✓ Right
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

✗ Wrong
if ch in "+-*/":
✓ Right
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

✗ Wrong
if not ch.isdigit() or i == len(s) - 1:
✓ Right
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.

07

Edge cases

Trailing spaces, as in " 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.

A product larger than 32 bits before a division

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.

08

Complexity

Time
O(n)
Space
O(n)
n is the length of 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.
09

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.