Basic Calculator II (LeetCode 227): Solution and Explanation
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
- Set
num = 0and the pending operatorop = '+'. - For each character: if it is a digit, set
num = num * 10 + digit. - If it is an operator or the last character, apply
optonum: pushnumfor+, push-numfor-, replace the top withtop * numfor*, or withtop / numtruncated toward zero for/. - Then set
opto the current character and resetnumto 0. Spaces are skipped by both checks. - Return the sum of the stack.
Step-by-step example
s = "3+2*2"
- Start with an empty stack and pending operator
+. - Read 3. The
+that follows completes it, and the pending+pushes 3. The stack is[3]; the pending operator becomes+. - Read 2. The
*that follows completes it, and the pending+pushes 2. The stack is[3, 2]; the pending operator becomes*. - 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]. - 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)1class Solution {
2 public int calculate(String s) {
3 Deque<Integer> stack = new ArrayDeque<>();
4 int num = 0;
5 char op = '+';
6 for (int i = 0; i < s.length(); i++) {
7 char ch = s.charAt(i);
8 if (Character.isDigit(ch)) {
9 num = num * 10 + (ch - '0');
10 }
11 if ((!Character.isDigit(ch) && ch != ' ') || i == s.length() - 1) {
12 if (op == '+') {
13 stack.push(num);
14 } else if (op == '-') {
15 stack.push(-num);
16 } else if (op == '*') {
17 stack.push(stack.pop() * num);
18 } else {
19 stack.push(stack.pop() / num);
20 }
21 op = ch;
22 num = 0;
23 }
24 }
25 int result = 0;
26 for (int v : stack) {
27 result += v;
28 }
29 return result;
30 }
31}1class Solution {
2public:
3 int calculate(string s) {
4 vector<long long> stack;
5 long long num = 0;
6 char op = '+';
7 for (int i = 0; i < (int)s.size(); i++) {
8 char ch = s[i];
9 if (isdigit(ch)) {
10 num = num * 10 + (ch - '0');
11 }
12 if ((!isdigit(ch) && ch != ' ') || i == (int)s.size() - 1) {
13 if (op == '+') {
14 stack.push_back(num);
15 } else if (op == '-') {
16 stack.push_back(-num);
17 } else if (op == '*') {
18 stack.back() *= num;
19 } else {
20 stack.back() /= num;
21 }
22 op = ch;
23 num = 0;
24 }
25 }
26 long long result = 0;
27 for (long long v : stack) {
28 result += v;
29 }
30 return (int)result;
31 }
32};Time and space complexity
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.
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 // 2is -2, but the problem wants truncation toward zero, so useint(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).