Problem
Evaluate a valid infix expression that contains non-negative integers, the operators +, -, * and /, and empty spaces. There are no parentheses. Division truncates toward zero.
Original: LeetCode 227: Basic Calculator II.
Examples
Example 1
`s = "3+2*2"``7`Example 2
`s = " 3/2 "``1`Example 3
`s = " 3+5 / 2 "``5`Constraints
1 <= s.length <= 3 * 10^5sconsists of integers and operators('+', '-', '*', '/')separated by some number of spaces.srepresents a valid expression.- All the integers in the expression are non-negative integers in the range
[0, 2^31 - 1]. - The answer is guaranteed to fit in a 32-bit integer.
Hints
Hint 1
Multiplication and division have higher precedence than addition and subtraction, and they associate left to right. The last number must be applied after the loop ends.
Hint 2
Operator precedence without parentheses can be handled by delaying + and - on a stack and applying * and / immediately to the previous term.
Solution
Tried it yourself? The approach, complexity, and code stay hidden until you choose.
Approach
Brute force. Tokenize, then run two passes: first * and /, then + and -. That is clear, but it needs an intermediate list.
Optimal. One pass: when you see an operator, apply the previous operator to the number you just finished. * and / update the top of the stack; + and - push a signed term. Sum the stack at the end.
Alternative. A shunting-yard conversion to postfix also works, and it extends more cleanly once parentheses return.
Complexity
- Time
- O(n)
O(n) time and O(n) space for the term stack. You can reduce space to O(1) by keeping only the running sum and the last term.
- Space
- O(n)
Code
def calculate(s: str) -> int:
stack: list[int] = []
number = 0
op = "+"
n = len(s)
for i in range(n + 1):
c = s[i] if i < n else "+"
if i < n and c == " ":
continue
if i < n and c.isdigit():
number = number * 10 + int(c)
continue
if op == "+":
stack.append(number)
elif op == "-":
stack.append(-number)
elif op == "*":
stack.append(stack.pop() * number)
else:
stack.append(int(stack.pop() / number))
if i < n:
op = c
number = 0
return sum(stack)
if __name__ == "__main__":
assert calculate("3+2*2") == 7
assert calculate(" 3/2 ") == 1
assert calculate(" 3+5 / 2 ") == 5
print("ok")import java.util.ArrayDeque;
public class BasicCalculatorII {
static int calculate(String s) {
var stack = new ArrayDeque<Integer>();
int number = 0;
char op = '+';
for (int i = 0; i <= s.length(); i++) {
char c = i < s.length() ? s.charAt(i) : '+';
if (i < s.length() && c == ' ') continue;
if (i < s.length() && Character.isDigit(c)) {
number = number * 10 + (c - '0');
continue;
}
switch (op) {
case '+' -> stack.addLast(number);
case '-' -> stack.addLast(-number);
case '*' -> stack.addLast(stack.removeLast() * number);
case '/' -> stack.addLast(stack.removeLast() / number);
default -> throw new IllegalStateException();
}
if (i < s.length()) op = c;
number = 0;
}
int sum = 0;
for (int v : stack) sum += v;
return sum;
}
public static void main(String[] args) {
if (calculate("3+2*2") != 7) throw new AssertionError();
if (calculate(" 3/2 ") != 1) throw new AssertionError();
if (calculate(" 3+5 / 2 ") != 5) throw new AssertionError();
System.out.println("ok");
}
}Edge cases
- Official samples: "3+2*2" equals 7, " 3/2 " equals 1, and " 3+5 / 2 " equals 5.
- Spaces can sit between numbers and operators. The last number must be flushed at the end of the string.
- Division truncates toward zero.
Follow-ups
- The constant-space version stores
totalandlastinstead of a stack: + and - add the previous last into total, and * and / update last in place.
Interview script
"I do not build a parser tree. I keep the previous operator and a stack of terms. Plus and minus push a signed number, and multiply and divide combine with the top term immediately, which gives * and / their higher precedence. At the end I sum the terms."
Source: LeetCode 227: Basic Calculator II
Sources
- LeetCode 20: Valid Parentheses
- Java SE 17 API: ArrayDeque
- HackerRank: Balanced Brackets
- LeetCode 735: Asteroid Collision
- LeetCode 1249: Minimum Remove to Make Valid Parentheses
- Java SE 17 API: HashSet
- LeetCode Discuss: Meta E4 interview experience (candidate report, March 2025)
- LeetCode 155: Min Stack
- Java SE 17 API: Math.min)
- LeetCode 496: Next Greater Element I
- Java SE 17 API: HashMap
- LeetCode 739: Daily Temperatures
- LeetCode 402: Remove K Digits
- Java SE 17 API: StringBuilder
- LeetCode 84: Largest Rectangle in Histogram
- HackerRank: Largest Rectangle
- LeetCode 71: Simplify Path
- LeetCode 394: Decode String
- LeetCode 150: Evaluate Reverse Polish Notation
- LeetCode 224: Basic Calculator
- LeetCode 227: Basic Calculator II
Sources (1)
- LeetCode 227: Basic Calculator IIleetcode.com