Basic Calculator (LeetCode 224): Solution and Explanation
Evaluate an arithmetic expression given as a string. It contains non-negative integers, plus and minus signs, parentheses and spaces, and a minus may also act as a unary negation. You must compute the result yourself without calling a built-in evaluator.
Watch it run step by step
Try your own input and write the code →Intuition
The textbook approach is to convert the expression to postfix with the shunting-yard algorithm and then evaluate it with a stack. That works for any operator set, but it is a lot of machinery for an expression that only has addition, subtraction and parentheses.
The simplification comes from noticing that with only plus and minus, every number ends up either added or subtracted from the total. If you know the effective sign in front of each number, you can just accumulate sign * num into a running result as you scan. Multi-digit numbers are built digit by digit, and each time you hit an operator you flush the current number into the result and remember the new sign.
Parentheses are the only thing that breaks this flat picture, because a minus in front of a group flips everything inside it. The fix is to treat a parenthesized group as a fresh sub-expression. When you see '(', you push the result so far and the sign that applies to the group onto a stack, then start a clean result of zero. When you see ')', you finish the inner result, multiply it by the saved sign, and add it to the saved outer result. Nested groups simply stack up, so one left-to-right pass handles any depth.
Approach: Single pass with a sign and a stack
- Initialize an empty
stack,num = 0,sign = 1andresult = 0. - For a digit, extend the current number with
num = num * 10 + int(char). - For '+' or '-', add
sign * numtoresult, resetnumto 0, and setsignto 1 or -1. - For '(', push
resultand thensign, and reset both so the group is evaluated on its own. - For ')', add the pending
sign * numtoresult, resetnum, multiplyresultby the popped sign, then add the popped outer result. - Spaces fall through every branch and are ignored. At the end, return
result + sign * numto flush the last number.
Step-by-step example
s = "2-(5-6)"
- Reading '2' sets
num = 2. The '-' adds 2 toresult, resetsnumand setssign = -1. - At '(' the stack becomes [2, -1], and
resultandsignreset to 0 and 1. - Inside the group, '5' sets
num = 5, then '-' makesresult = 5andsign = -1, and '6' setsnum = 6. - At ')' the inner result becomes 5 - 6 = -1. Multiplying by the popped sign -1 gives 1, and adding the popped 2 gives
result = 3. - The string ends with
num = 0, so the function returns 3 + (-1 × 0) = 3.
Code: Python, Java, C++
1class Solution:
2 def calculate(self, s: str) -> int:
3 stack = []
4 num = 0
5 sign = 1
6 result = 0
7
8 for char in s:
9 if char.isdigit():
10 num = num * 10 + int(char)
11 elif char == '+':
12 result += sign * num
13 num = 0
14 sign = 1
15 elif char == '-':
16 result += sign * num
17 num = 0
18 sign = -1
19 elif char == '(':
20 stack.append(result)
21 stack.append(sign)
22 result = 0
23 sign = 1
24 elif char == ')':
25 result += sign * num
26 num = 0
27 result *= stack.pop() # sign
28 result += stack.pop() # previous result
29
30 return result + sign * num1class Solution {
2 public int calculate(String s) {
3 Stack<Integer> stack = new Stack<>();
4 int num = 0, sign = 1, result = 0;
5
6 for (char c : s.toCharArray()) {
7 if (Character.isDigit(c)) {
8 num = num * 10 + (c - '0');
9 } else if (c == '+') {
10 result += sign * num;
11 num = 0;
12 sign = 1;
13 } else if (c == '-') {
14 result += sign * num;
15 num = 0;
16 sign = -1;
17 } else if (c == '(') {
18 stack.push(result);
19 stack.push(sign);
20 result = 0;
21 sign = 1;
22 } else if (c == ')') {
23 result += sign * num;
24 num = 0;
25 result *= stack.pop();
26 result += stack.pop();
27 }
28 }
29 return result + sign * num;
30 }
31}1class Solution {
2public:
3 int calculate(string s) {
4 stack<int> stk;
5 int num = 0, sign = 1, result = 0;
6
7 for (char c : s) {
8 if (isdigit(c)) {
9 num = num * 10 + (c - '0');
10 } else if (c == '+') {
11 result += sign * num;
12 num = 0;
13 sign = 1;
14 } else if (c == '-') {
15 result += sign * num;
16 num = 0;
17 sign = -1;
18 } else if (c == '(') {
19 stk.push(result);
20 stk.push(sign);
21 result = 0;
22 sign = 1;
23 } else if (c == ')') {
24 result += sign * num;
25 num = 0;
26 result *= stk.top(); stk.pop();
27 result += stk.top(); stk.pop();
28 }
29 }
30 return result + sign * num;
31 }
32};Time and space complexity
O(n)
Each character is processed once with constant work, and every push onto the stack is matched by exactly one pair of pops at the closing parenthesis.
O(n)
The stack holds two values per open parenthesis, so deeply nested input such as many leading '(' characters uses space proportional to the string length.
Other approaches
Recursive descent (time O(n), space O(n))
Write a function that parses terms and calls itself when it sees '(', returning both the value and the index where the group ended. It mirrors the grammar directly and extends easily to multiplication, but uses the call stack instead of an explicit one.
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 is the general solution for many operators and precedences, but needs special handling for unary minus and is far more code than this problem requires.
Common mistakes
- Forgetting to flush the final number. If the expression ends in a digit,
numstill holds it, which is why the return addssign * num. - Treating each digit as its own number. You must accumulate multi-digit values with
num * 10 + digitbefore applying the sign. - Pushing only the result at '(' and losing the sign in front of the group. Without the saved sign, an expression like '1-(2+3)' evaluates to 6 instead of -4.
- Not resetting
numafter ')'. The inner number has already been applied, and leaving it set would add it a second time.
Frequently asked questions
How does Basic Calculator handle a unary minus?
A leading '-' or a '-' right after '(' is processed like any other minus: it adds the current num, which is 0, and sets sign = -1. The next number or group is then subtracted, which is exactly what unary negation means.
Why is a stack needed in Basic Calculator?
Parentheses create nested scopes. When a group closes, you need the result and sign that were in effect just before it opened, and a stack returns the most recently saved context first, which matches how parentheses nest.
What is the time complexity of Basic Calculator?
It is O(n), because the string is scanned once and each character costs constant time. The stack adds O(n) space only in the worst case of deep nesting.
How do I extend this to multiplication and division?
That is the Basic Calculator II and III family. You keep the last term separately so that '*' and '/' can bind to it before it is added to the total, and combine that with the same stack trick for parentheses.