Basic Calculator II (LeetCode 227): Solution and Explanation

Medium
Math
String
Stack

Evaluate a string such as 3+2*2 that contains non-negative integers, +, -, *, / and spaces. * and / come before + and -, and division truncates toward zero.

Intuition

Without parentheses, every expression of this kind is a sum of terms. 3 + 2*2 - 8/4 is the terms 3, 2*2 and -8/4 added together. A + or - always starts a new term, and a * or / always extends the term in progress.

That suggests a stack of signed terms. When the operator before a number is +, push the number. When it is -, push its negation, so subtraction becomes adding a negative term. When it is * or /, the number belongs to the latest term, so pop that term, combine, and push the result back.

You cannot apply an operator until its right operand is complete, so remember the operator that came before the current number and apply it once you reach the next operator or the end of the string. After the scan, every term is final and the answer is the sum of the stack.

Approach: Stack of signed terms

  1. Set num = 0 and the pending operator op = '+'.
  2. For each character: if it is a digit, set num = num * 10 + digit.
  3. If it is an operator or the last character, apply op to num: push num for +, push -num for -, replace the top with top * num for *, or with top / num truncated toward zero for /.
  4. Then set op to the current character and reset num to 0. Spaces are skipped by both checks.
  5. Return the sum of the stack.

Step-by-step example

s = "3+2*2"
  1. Start with an empty stack and pending operator +.
  2. Read 3. The + that follows completes it, and the pending + pushes 3. The stack is [3]; the pending operator becomes +.
  3. Read 2. The * that follows completes it, and the pending + pushes 2. The stack is [3, 2]; the pending operator becomes *.
  4. Read the final 2 and reach the end of the string. The pending * pops 2, multiplies by 2 and pushes 4. The stack is [3, 4].
  5. Add the terms: 3 + 4 = 7.

Code: Python, Java, C++

1class Solution:
2    def calculate(self, s: str) -> int:
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)
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(n)

Each character is read once, each number causes one push or one pop-and-push, and the final sum walks the stack once.

Space

O(n)

The stack holds one value per term, which is at most about half the length of the string.

Other approaches

Keep only the last term (time O(n), space O(1))

Only the top of the stack is ever modified, so keep a running result for all finished terms and a variable last for the current term. On + or -, add last to result and start a new last; on * or /, update last. This brings the space down to O(1).

Shunting-yard to postfix (time O(n), space O(n))

Convert the infix expression to postfix with an operator stack, then evaluate the postfix with a value stack. It handles parentheses and more operators, but it is far more machinery than this problem needs.

Common mistakes

  • Forgetting to apply the last pending operator. The final number has no operator after it, so also apply when you reach the last character.
  • Using floor division for negative terms. In Python -3 // 2 is -2, but the problem wants truncation toward zero, so use int(a / b).
  • Treating a space as an operator. A space must neither apply the pending operator nor reset num.
  • Adding numbers as you go. A + cannot be applied right away, because a following * may take its right operand.

Frequently asked questions

Why push negative numbers for subtraction?

Storing the sign with the number turns the whole expression into a plain sum of terms. A later * or / then acts on the signed value, and the final step is a single addition.

Why does the code apply the previous operator, not the current one?

An operator needs its right operand, which is only complete when the next operator or the end of the string is reached. So the operator before the number is remembered and applied at that point.

How is this different from Basic Calculator?

Basic Calculator has parentheses and only + and -, so its stack saves the sign and partial result at each (. Here there are no parentheses but * and / bind tighter, so the stack holds terms of a sum.

What is the time complexity of Basic Calculator II?

O(n) time. The stack version uses O(n) space, and keeping only the last term reduces that to O(1).