Try it first — give it 25 minutes
0/4 revealedStuck? Take one hint at a time. The struggle is where the pattern sticks.
The problem in plain English
You get a string s with non-negative integers, the operators + - * /, and spaces. There are no parentheses and no unary minus. Evaluate it with normal precedence: * and / happen before + and -, and operators of the same level go left to right. Division truncates toward zero. You can't use a built-in eval.
The expression is always valid. s has up to 3 × 10⁵ characters, and every intermediate result fits in a 32-bit integer.
Example: "3+2*2" → 7, because 2*2 happens first. " 3/2 " → 1.
Start with brute force
Do it the way you learned in school. Tokenize the string. Repeatedly find the leftmost * or /, compute it, and replace the three tokens with the result. When none are left, do the same for + and -.
It's correct, but every replacement shifts the rest of the token list, which costs O(n), and there can be about n/2 operators. With 3 × 10⁵ characters that's on the order of 10¹⁰ moves. We want a single left-to-right pass.
Building the intuition
Look at 14 - 3/2 + 2*3*4 and put brackets around what precedence really means:
14 - (3/2) + (2*3*4)The expression is just a sum of terms. + and - separate the terms. * and / live inside a term. So:
- When you meet
+ x, a new term+xstarts. - When you meet
- x, a new term−xstarts. Store the sign with the term, and subtraction becomes adding a negative. - When you meet
* xor/ x, you're not starting anything. You're changing the most recent term.
"Change the most recent thing" means a stack again. Push each term as it starts, modify the top for * and /, and add everything up at the end.
One practical wrinkle: you read characters, not numbers. You only know 14 is complete when you reach the - after it. So when you finish a number, the operator to apply is the previous one, the one before the number. Keep it in a variable op, starting as + so the first number is simply pushed.
The optimal approach
stack = [],num = 0,op = '+'.- For each index
iwith characterc:- If
cis a digit:num = num · 10 + digit. - If
cis an operator oriis the last index, the number is complete. Applyop:+: pushnum;-: push−num;*: replace the top withtop · num;/: replace the top withtop / num, truncated toward zero.
- Then set
op = candnum = 0.
- If
- Return the sum of the stack.
Spaces are skipped automatically, since they're neither digits nor operators. The i == last check matters even when the last character is a space: it still flushes the final number.
The subtle detail is truncation of negative terms. Because -3 is stored as a negative term, 14-3/2 computes -3 / 2. It must give -1, so the result is 14 − 1 = 13. Python's // gives -2 and the answer 12. Use int(a / b) in Python and Math.trunc in JavaScript. C++ and Java already truncate.
The code
Every solution below is tested against the examples and edge cases before it ships. Pick your language — we'll remember it.
class Solution:
def calculate(self, s: str) -> int:
stack = [] # signed terms; the answer is their sum
num = 0 # the number we are reading right now
op = "+" # the operator that came BEFORE num
for i, c in enumerate(s):
if c.isdigit():
num = num * 10 + int(c)
# an operator (or the end of the string) means num is complete
if c in "+-*/" or i == len(s) - 1:
if op == "+":
stack.append(num)
elif op == "-":
stack.append(-num)
elif op == "*":
stack.append(stack.pop() * num) # * binds tighter: fold into the last term now
else:
# truncate toward zero; // would floor -3 // 2 to -2 instead of -1
stack.append(int(stack.pop() / num))
op = c
num = 0
return sum(stack)class Solution {
public:
int calculate(string s) {
vector<int> stack; // signed terms; the answer is their sum
int num = 0; // the number we are reading right now
char op = '+'; // the operator that came BEFORE num
int n = s.size();
for (int i = 0; i < n; i++) {
char c = s[i];
if (isdigit(c)) num = num * 10 + (c - '0');
// an operator (or the end of the string) means num is complete
if (c == '+' || c == '-' || c == '*' || c == '/' || i == n - 1) {
if (op == '+') stack.push_back(num);
else if (op == '-') stack.push_back(-num);
else if (op == '*') stack.back() *= num; // * binds tighter: fold into the last term now
else stack.back() /= num; // C++ division already truncates toward zero
op = c;
num = 0;
}
}
int result = 0;
for (int term : stack) result += term;
return result;
}
};class Solution {
public int calculate(String s) {
Deque<Integer> stack = new ArrayDeque<>(); // signed terms; the answer is their sum
int num = 0; // the number we are reading right now
char op = '+'; // the operator that came BEFORE num
int n = s.length();
for (int i = 0; i < n; i++) {
char c = s.charAt(i);
if (Character.isDigit(c)) num = num * 10 + (c - '0');
// an operator (or the end of the string) means num is complete
if (c == '+' || c == '-' || c == '*' || c == '/' || i == n - 1) {
if (op == '+') stack.push(num);
else if (op == '-') stack.push(-num);
else if (op == '*') stack.push(stack.pop() * num); // * binds tighter: fold into the last term now
else stack.push(stack.pop() / num); // Java division already truncates toward zero
op = c;
num = 0;
}
}
int result = 0;
for (int term : stack) result += term;
return result;
}
}/**
* @param {string} s
* @return {number}
*/
var calculate = function (s) {
const stack = []; // signed terms; the answer is their sum
let num = 0; // the number we are reading right now
let op = "+"; // the operator that came BEFORE num
for (let i = 0; i < s.length; i++) {
const c = s[i];
if (c >= "0" && c <= "9") num = num * 10 + (c.charCodeAt(0) - 48);
// an operator (or the end of the string) means num is complete
if (c === "+" || c === "-" || c === "*" || c === "/" || i === s.length - 1) {
if (op === "+") stack.push(num);
else if (op === "-") stack.push(-num);
else if (op === "*") stack.push(stack.pop() * num); // * binds tighter: fold into the last term now
else stack.push(Math.trunc(stack.pop() / num)); // truncate toward zero, not Math.floor
op = c;
num = 0;
}
}
return stack.reduce((sum, term) => sum + term, 0);
};Dry run
s = "14-3/2"
| i | c | num after | event | op used | stack after | op after |
|---|---|---|---|---|---|---|
| 0 | 1 | 1 | digit | [] | + | |
| 1 | 4 | 14 | digit | [] | + | |
| 2 | - | 0 | number done | + → push 14 | [14] | - |
| 3 | 3 | 3 | digit | [14] | - | |
| 4 | / | 0 | number done | - → push −3 | [14, -3] | / |
| 5 | 2 | 2 → 0 | digit, and last index | / → top = trunc(−3 / 2) = −1 | [14, -1] |
The sum of the stack is 14 + (−1) = 13.
Complexity
- Time: O(n). One pass over the characters, O(1) work each, then one pass to sum the stack.
- Space: O(n). An expression like
1+1+1+…pushes one term per number.
Edge cases and traps
- Applying the new operator instead of the previous one. When you read
-after14, the14belongs to the+before it. - Forgetting the last number. Without the
i == lastcheck,"3+2"returns 3. - Floor division on negative terms.
"1-3/2"must be0, not-1. - Multi-digit numbers. Build them with
num · 10 + digit. Don't push each digit. - Spaces everywhere.
" 3+5 / 2 "is5. Never treat a space as the end of a number. - Left-to-right for
*and/.100/10/3is(100/10)/3 = 3. Folding into the top term does this naturally.
Say it in the interview
"Precedence just means the expression is a sum of terms: plus and minus start a new term, times and divide modify the current one. I'll keep a stack of signed terms. I read digits into a number, and when I hit an operator or the end, I apply the previous operator. Plus pushes the number, minus pushes its negative, and times or divide replace the top. Division truncates toward zero, which I handle explicitly in Python. The answer is the sum of the stack. That's O(n) time and O(n) space."
Follow-ups interviewers ask
- "Can you do it in O(1) space?" Yes. You only ever touch the top term, so keep
lastTermandresultin variables. On+or-, addlastTermtoresultand start a new one. On*or/, updatelastTerm. At the end, returnresult + lastTerm. - "What if there are parentheses?" That's Basic Calculator III. On
(, recurse (or push your state onto a stack), evaluate the inside, and treat the result as a number. - "How is this related to Evaluate Reverse Polish Notation?" RPN has no precedence to resolve, so one operand stack is enough. Here the operator order is implicit, so you resolve
*and/eagerly and save+and-for the end.
Practise the same idea
This is Day 35 of a free 90-day plan 🐸
90 problems in the order that builds on itself, one a day, with a walkthrough like this for each. Tick them off and keep your streak.
Get the full roadmap — free