Basic Calculator
Hard
Topics
Given a string s representing a valid expression, implement a basic calculator to evaluate it and return the result. The expression contains non-negative integers, +, -, (, ), spaces, and unary minus.
Example 1
+, - and brackets, so no precedence — but a leading - before a bracket flips the sign of everything inside it. Pushing the running total and the current sign at (, and folding back at ), handles arbitrary nesting. Result: 2.Input: s = "1 + 1" Output: 2
Example 2
Input: s = " 2-1 + 2 " Output: 3
Example 3
Input: s = "(1+(4+5+2)-3)+(6+8)" Output: 23
Constraints
- 1 <= s.length <= 20
- s consists of digits, '+', '-', '(', ')', and spaces.
- s represents a valid expression.
Editorial — intuition, approach, complexity and pitfalls
Intuition
The textbook answer is to parse: tokenise, build a tree or convert to postfix with the shunting-yard algorithm, then evaluate. That works and is the right tool when there are many operators with different precedences. Here it is heavier than the problem needs.
What makes a shortcut available is the restricted grammar: only +, -, parentheses and non-negative integers. There is no multiplication, so there is no precedence to resolve — the expression can be evaluated strictly left to right. That removes the only reason to build a tree.
Without precedence, every number in the whole expression contributes to the final answer with either a + or a - in front of it, and the parentheses only serve to flip signs. 1 - (2 - 3) is just 1 - 2 + 3. So we can sweep once, keeping a running total and the sign that applies to the next number.
The only thing a parenthesis changes is that the result inside must be computed independently and then folded in with the sign that preceded it. That is a save-and-restore, which is exactly a stack:
- On
(, push the result accumulated so far and the sign sitting in front of the bracket, then reset both to start a fresh sub-expression. - On
), close out the sub-expression, multiply it by the saved sign, and add the saved outer result back.
Note what is not on the stack: operators, tokens, or sub-expression trees. Only two integers per nesting level. The structure is a running total plus a sign, and the stack is there to remember suspended ones.
Approach
- Keep
num(digits being accumulated),sign(+1 or -1, applying to the next number), andresult(the running total at this nesting level). - On a digit, extend
numwithnum * 10 + digit— numbers are multi-digit, so they cannot be read one character at a time. - On
+or-, commit the pending number withresult += sign * num, resetnumto 0, and setsign. - On
(, pushresultthensign, and reset both. The push order matters only in that the pop order must mirror it. - On
), commit the pending number, thenresult = result * popped_sign + popped_result. - After the loop, commit the final pending number:
result + sign * num. Nothing else flushes it, since the expression does not end in an operator.
Spaces need no handling at all — none of the branches match them, so they are skipped naturally.
Dry Run
s = "(1+(4+5+2)-3)+(6+8)", expected 23.
ch action result sign stack
( push result,sign; reset 0 +1 [0,1]
1 num=1
+ commit: result += +1*1 1 +1 [0,1]
( push result,sign; reset 0 +1 [0,1,1,1]
4 num=4
+ commit: result += +1*4 4 +1 [0,1,1,1]
5 num=5
+ commit: result += +1*5 9 +1 [0,1,1,1]
2 num=2
) commit -> 11, then 11*pop(1) + pop(1) = 12 12 +1 [0,1]
- sign = -1 12 -1 [0,1]
3 num=3
) commit -> 12-3 = 9, then 9*pop(1) + pop(0) = 9 9 -1 []
+ sign = +1 9 +1 []
( push result,sign; reset 0 +1 [9,1]
6 num=6
+ commit: result += +1*6 6 +1 [9,1]
8 num=8
) commit -> 14, then 14*pop(1) + pop(9) = 23 23 +1 []
end result + sign*num = 23 + 0 = 23The step to study is the first ) at the inner bracket: result is the value of 4+5+2 alone, because ( reset it, and the saved 1 is what the outer level had accumulated. Folding is multiply-then-add, in that order — the sign applies to the bracket's value, not to the outer total.
Complexity
- Time — O(n): one pass, constant work per character. Same as shunting-yard, but with no token list and no second evaluation pass.
- Space — O(n): the stack holds two integers per open parenthesis, so it is O(d) in nesting depth d, which is O(n) in the worst case of
((((...)))). Notably this is not O(n) in the number of tokens — a long flat expression like1+2+3+...+1000uses no stack at all.
Common Pitfalls
- Reading digits one character at a time. Inputs contain multi-digit numbers, so
num = num * 10 + dis required; treating "42" as 4 then 2 is the most common failure. - Forgetting the final commit after the loop. The last number is still pending in
numwhen the string ends, so returningresultalone drops it. - Popping in the wrong order. Push is result-then-sign, so pop must be sign-then-result; swapping them silently corrupts every nested expression.
- Adding before multiplying on
). The saved sign multiplies the bracket's value; applying it to the sum of bracket and outer result gives the wrong sign on the outer part. - Not resetting
signto +1 after(. A leading-outside a bracket would otherwise leak into the first term inside it. - Assuming unary minus cannot appear. Expressions like
-(3+4)or(-2+1)work with this scheme becausesignstarts at +1 andnumat 0, so a leading-commits a harmless+1*0and then sets the sign — worth checking rather than assuming. - Reaching for a full expression parser. Correct, but it is far more code than a problem without precedence requires, and the follow-up (add
*and/) is better answered by extending this scan than by having started with shunting-yard.
Full Solution — all languages
class Solution:
def calculate(self, s):
stack = []
num = 0
sign = 1
res = 0
for c in s:
if c.isdigit():
num = num * 10 + int(c)
elif c == '+':
res += sign * num
num = 0
sign = 1
elif c == '-':
res += sign * num
num = 0
sign = -1
elif c == '(':
stack.append(res)
stack.append(sign)
res = 0
sign = 1
elif c == ')':
res += sign * num
num = 0
res *= stack.pop()
res += stack.pop()
res += sign * num
return resimport java.util.*;
class Solution {
public int calculate(String s) {
Deque<Long> stack = new ArrayDeque<>();
long num = 0, sign = 1, res = 0;
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (c >= '0' && c <= '9') num = num * 10 + (c - '0');
else if (c == '+') {
res += sign * num;
num = 0;
sign = 1;
} else if (c == '-') {
res += sign * num;
num = 0;
sign = -1;
} else if (c == '(') {
stack.push(res);
stack.push(sign);
res = 0;
sign = 1;
} else if (c == ')') {
res += sign * num;
num = 0;
res *= stack.pop();
res += stack.pop();
}
}
res += sign * num;
return (int) res;
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: int calculate(string s) {
vector<long long> stack;
long long num = 0, sign = 1, res = 0;
for (char c : s) {
if (c >= '0' && c <= '9') num = num * 10 + (c - '0');
else if (c == '+') {
res += sign * num;
num = 0;
sign = 1;
} else if (c == '-') {
res += sign * num;
num = 0;
sign = -1;
} else if (c == '(') {
stack.push_back(res);
stack.push_back(sign);
res = 0;
sign = 1;
} else if (c == ')') {
res += sign * num;
num = 0;
res *= stack.back();
stack.pop_back();
res += stack.back();
stack.pop_back();
}
}
res += sign * num;
return (int)res;
}
};/**
* @param {string} s
* @return {number}
*/ var calculate = function(s) {
const stack = [];
let num = 0, sign = 1, res = 0;
for (let i = 0; i < s.length; i++) {
const c = s[i];
if (c >= '0' && c <= '9') num = num * 10 + (c.charCodeAt(0) - 48);
else if (c === '+') {
res += sign * num;
num = 0;
sign = 1;
} else if (c === '-') {
res += sign * num;
num = 0;
sign = -1;
} else if (c === '(') {
stack.push(res);
stack.push(sign);
res = 0;
sign = 1;
} else if (c === ')') {
res += sign * num;
num = 0;
res *= stack.pop();
res += stack.pop();
}
}
res += sign * num;
return res;
};