15% off all plans & roadmaps Use code
See plansBasic Calculator
- LeetCode 224
- Hard
- Stack Patterns
- Expression Evaluation (RPN/Infix)
Updated
TL;DR: You must evaluate a string of digits, plus, minus and parentheses without using eval. Scan the string once, and at each open parenthesis push the outer total and sign onto a stack so the group can finish first.
Problem
Given a string s that represents a valid expression, implement a basic calculator that evaluates it. Return the result of the evaluation.
Note: You may not use any built-in function that evaluates a string as a math expression, such as eval().
Example 1
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 <= 3 * 10^5sconsists of digits,'+','-','(',')', and' '.srepresents a valid expression.'+'is not used as a unary operation (for example"+1"or"+(2 + 3)"is invalid).'-'may be used as a unary operation (for example"-1"or"-(2 + 3)"is valid).- There are no two consecutive operators in the input.
- Every number and running calculation fits in a signed 32-bit integer.
Constraints that matter
- The length can reach 3 * 10^5, so any method that rescans or rebuilds the string once per group costs O(n^2) on large nested inputs.
- Nesting can go about n / 2 levels deep, so the saved state can need O(n) space. You need a stack, not a fixed set of variables.
- Unary minus is allowed but unary plus is not. A sign comes only from a
-placed before a number or a group, so one sign variable is enough. - Values fit in 32 bits, so plain int arithmetic is safe in Java, C++ and C#. Python integers never overflow.
Hints
Hint 1
This is expression evaluation with a stack.
Hint 2
Treat the innermost parentheses as a flat expression.
Solution
Intuition
This is expression evaluation with a stack. The whole expression is a sum of signed terms, and a parenthesis group is one term whose value comes from the expression inside it.
Picture a pile of sticky notes on a desk. Each open parenthesis writes the running total and its sign on a new note and places it on top. The stack is that pile of notes, and each closing parenthesis pulls the top note off to finish the outer sum.
What to notice: the group must be evaluated before it joins the outer total, yet the outer total is not finished. You must remember that total and the sign that applies to the group. Groups nest, so the most recently saved state must come back first. That is last in, first out order, which is what a stack gives you.
Once you see that, one left-to-right scan is enough. Digits build a number. An operator or a closing parenthesis finishes a term. An opening parenthesis saves the state, and a closing one restores it.
Worked example
Input: s = "(10-(2+3))+((4+5)-(6-7))+8" Output: 23 Explanation: The group (10-(2+3)) evaluates to 5. The group ((4+5)-(6-7)) evaluates to 9 minus -1, which is 10. The total is 5 + 10 + 8, which is 23.
Approach 1: Brute force
Treat the innermost parentheses as a flat expression. Evaluate that group with a plain left-to-right pass over digits, + and -. Replace the group with its value in the string, then repeat until no parentheses remain. Most people write this first, and it is correct.
Steps
- Find the last
(in the string. It is the innermost open parenthesis. - Find the first
)after it. Those two characters bound the innermost group. - Evaluate the text between them with a flat pass. A
-flips the sign of the next term, so--1becomes +1. - Replace the group, including both parentheses, with the value written as text.
- Repeat until no
(remains, then run the flat pass on the whole string.
Dry run
Start with (10-(2+3))+((4+5)-(6-7))+8.
Round 1: the last ( sits in (6-7), which evaluates to -1. The string becomes (10-(2+3))+((4+5)--1)+8.
Round 2: the last ( sits in (2+3), which evaluates to 5. The string becomes (10-5)+((4+5)--1)+8.
Round 3: the last ( sits before 4+5, which evaluates to 9. The string becomes (10-5)+(9--1)+8.
Round 4: 9--1 evaluates to 10, because two minus signs make a plus. The string becomes (10-5)+10+8.
Round 5: (10-5) evaluates to 5. The string becomes 5+10+8. No parentheses remain, so the flat pass returns 23.
Complexity
| Time | O(n^2) |
|---|---|
| Space | O(n) |
Let n be the length of s. Each round removes one ( and never adds one, so there are at most n / 2 rounds. Each round scans the string to find the group, evaluates it, and builds a new string, which costs O(n) work. Multiplying about n / 2 rounds by O(n) work per round gives O(n^2) time, and the strings it builds use O(n) space.
PythonTested in our runner
from typing import List, Optional
class Solution:
def calculate(self, s: str) -> int:
def eval_flat(t: str) -> int:
# Digits, + and - only. A '-' flips the sign of the next term.
total = 0
sgn = 1
num = 0
in_num = False
for ch in t:
if ch.isdigit():
num = num * 10 + int(ch)
in_num = True
else:
if in_num:
total += sgn * num
num = 0
in_num = False
sgn = 1
if ch == '-':
sgn = -sgn
if in_num:
total += sgn * num
return total
while '(' in s:
i = s.rfind('(')
j = s.index(')', i)
value = eval_flat(s[i + 1:j])
s = s[:i] + str(value) + s[j + 1:]
return eval_flat(s)JavaTested in our runner
import java.util.*;
class Solution {
public int calculate(String s) {
while (s.indexOf('(') >= 0) {
int i = s.lastIndexOf('(');
int j = s.indexOf(')', i);
int value = evalFlat(s.substring(i + 1, j));
s = s.substring(0, i) + value + s.substring(j + 1);
}
return evalFlat(s);
}
// Digits, + and - only. A '-' flips the sign of the next term.
private int evalFlat(String t) {
int total = 0;
int sgn = 1;
int num = 0;
boolean inNum = false;
for (int k = 0; k < t.length(); k++) {
char ch = t.charAt(k);
if (Character.isDigit(ch)) {
num = num * 10 + (ch - '0');
inNum = true;
} else {
if (inNum) {
total += sgn * num;
num = 0;
inNum = false;
sgn = 1;
}
if (ch == '-') {
sgn = -sgn;
}
}
}
if (inNum) {
total += sgn * num;
}
return total;
}
}C++Tested in our runner
#include <string>
using namespace std;
class Solution {
public:
int calculate(string s) {
while (s.find('(') != string::npos) {
size_t i = s.rfind('(');
size_t j = s.find(')', i);
int value = evalFlat(s.substr(i + 1, j - i - 1));
s = s.substr(0, i) + to_string(value) + s.substr(j + 1);
}
return evalFlat(s);
}
private:
// Digits, + and - only. A '-' flips the sign of the next term.
int evalFlat(const string& t) {
int total = 0;
int sgn = 1;
int num = 0;
bool inNum = false;
for (char ch : t) {
if (ch >= '0' && ch <= '9') {
num = num * 10 + (ch - '0');
inNum = true;
} else {
if (inNum) {
total += sgn * num;
num = 0;
inNum = false;
sgn = 1;
}
if (ch == '-') {
sgn = -sgn;
}
}
}
if (inNum) {
total += sgn * num;
}
return total;
}
};JavaScriptTested in our runner
var calculate = function(s) {
// Digits, + and - only. A '-' flips the sign of the next term.
const evalFlat = (t) => {
let total = 0;
let sgn = 1;
let num = 0;
let inNum = false;
for (const ch of t) {
if (ch >= '0' && ch <= '9') {
num = num * 10 + (ch.charCodeAt(0) - 48);
inNum = true;
} else {
if (inNum) {
total += sgn * num;
num = 0;
inNum = false;
sgn = 1;
}
if (ch === '-') {
sgn = -sgn;
}
}
}
if (inNum) {
total += sgn * num;
}
return total;
};
while (s.indexOf('(') !== -1) {
const i = s.lastIndexOf('(');
const j = s.indexOf(')', i);
const value = evalFlat(s.substring(i + 1, j));
s = s.substring(0, i) + String(value) + s.substring(j + 1);
}
return evalFlat(s);
};GoTested in our runner
import (
"strconv"
"strings"
)
func calculate(s string) int {
for strings.IndexByte(s, '(') >= 0 {
i := strings.LastIndexByte(s, '(')
j := i + strings.IndexByte(s[i:], ')')
value := evalFlat(s[i+1 : j])
s = s[:i] + strconv.Itoa(value) + s[j+1:]
}
return evalFlat(s)
}
// evalFlat handles digits, + and - only. A '-' flips the sign of the next term.
func evalFlat(t string) int {
total, sgn, num := 0, 1, 0
inNum := false
for i := 0; i < len(t); i++ {
ch := t[i]
if ch >= '0' && ch <= '9' {
num = num*10 + int(ch-'0')
inNum = true
} else {
if inNum {
total += sgn * num
num = 0
inNum = false
sgn = 1
}
if ch == '-' {
sgn = -sgn
}
}
}
if inNum {
total += sgn * num
}
return total
}C#Tested in our runner
public class Solution {
public int calculate(string s) {
while (s.IndexOf('(') >= 0) {
int i = s.LastIndexOf('(');
int j = s.IndexOf(')', i);
int value = EvalFlat(s.Substring(i + 1, j - i - 1));
s = s.Substring(0, i) + value.ToString() + s.Substring(j + 1);
}
return EvalFlat(s);
}
// Digits, + and - only. A '-' flips the sign of the next term.
private static int EvalFlat(string t) {
int total = 0;
int sgn = 1;
int num = 0;
bool inNum = false;
foreach (char ch in t) {
if (ch >= '0' && ch <= '9') {
num = num * 10 + (ch - '0');
inNum = true;
} else {
if (inNum) {
total += sgn * num;
num = 0;
inNum = false;
sgn = 1;
}
if (ch == '-') {
sgn = -sgn;
}
}
}
if (inNum) {
total += sgn * num;
}
return total;
}
}The Expression Evaluation (RPN/Infix) infographic is part of Pro
A one-page visual of the pattern: when it applies, the steps and the invariant to keep.
Unlock the infographicSolution pattern
Expression Evaluation (RPN/Infix)
Part of Stack Patterns
Approach 2: One-pass stackOptimalExpression Evaluation (RPN/Infix)
What's slow in the brute force is the rework. Each round rescans the string, rebuilds it, and evaluates one group in isolation, so the outer text is copied again and again.
The insight that fixes it is that you never need to rebuild. When a group opens, push the outer total and sign onto a stack. When it closes, pop them and fold the group's value in. One left-to-right pass handles every nesting level.
Why it is correct. At every moment, the stack holds the partial total and sign of each unfinished group, from outermost to innermost. Closing a parenthesis applies the saved sign to the finished group and adds it to the waiting total, so the value is rebuilt exactly. No term is skipped or reordered, so the final result equals the value of the full expression.
Steps
- Keep
result(the total so far),sign(1 or -1, the sign of the next term) andnum(the number being read). - On a digit, set
num = num * 10 + digit. - On
+or-, addsign * numtoresult, setnumto 0, then setsignto 1 for+or -1 for-. - On
(, pushresult, pushsign, then setresultto 0 andsignto 1. - On
), addsign * numtoresultand setnumto 0. Pop the sign and multiplyresultby it. Pop the outer result and add it. - Skip spaces. At the end, return
result + sign * num.
Dry run
Trace the table on the example. Each ) pops the sign first, because the sign was pushed second. After the row for the second ), the sign column still reads -1, but num is 0, so that stale sign adds nothing.
| Step | Read | result | sign | num | stack (bottom to top) |
|---|---|---|---|---|---|
| 1 | ( | 0 | 1 | 0 | [(0,1)] |
| 2 | 1 then 0 | 0 | 1 | 10 | [(0,1)] |
| 3 | - | 10 | -1 | 0 | [(0,1)] |
| 4 | ( | 0 | 1 | 0 | [(0,1), (10,-1)] |
| 5 | 2 then + | 2 | 1 | 0 | [(0,1), (10,-1)] |
| 6 | 3 | 2 | 1 | 3 | [(0,1), (10,-1)] |
| 7 | ) inner | 5, then -5, then 5 | 1 | 0 | [(0,1)] |
| 8 | ) outer | 5 | 1 | 0 | [] |
| 9 | + | 5 | 1 | 0 | [] |
| 10 | ( | 0 | 1 | 0 | [(5,1)] |
| 11 | ( | 0 | 1 | 0 | [(5,1), (0,1)] |
| 12 | 4 then + | 4 | 1 | 0 | [(5,1), (0,1)] |
| 13 | 5 then ) | 9 | 1 | 0 | [(5,1)] |
| 14 | - | 9 | -1 | 0 | [(5,1)] |
| 15 | ( | 0 | 1 | 0 | [(5,1), (9,-1)] |
| 16 | 6 then - | 6 | -1 | 0 | [(5,1), (9,-1)] |
| 17 | 7 then ) | 10 | -1 | 0 | [(5,1)] |
| 18 | ) group | 15 | -1 | 0 | [] |
| 19 | + | 15 | 1 | 0 | [] |
| 20 | 8 | 15 | 1 | 8 | [] |
| end | return result + sign * num | 23 | 1 | 8 | [] |
Complexity
| Time | O(n) |
|---|---|
| Space | O(n) |
Let n be the length of s. The loop reads each character once, and every branch does constant work, so the scan costs O(n). Each ( pushes two values and each ) pops two, so the stack holds at most two values per open parenthesis. The nesting depth is at most about n / 2, so the stack uses O(n) space.
PythonTested in our runner
from typing import List, Optional
class Solution:
def calculate(self, s: str) -> int:
stack = [] # saved (result, sign) pairs for outer levels
result = 0
sign = 1
num = 0
for ch in s:
if ch.isdigit():
num = num * 10 + int(ch)
elif ch == '+':
result += sign * num
num = 0
sign = 1
elif ch == '-':
result += sign * num
num = 0
sign = -1
elif ch == '(':
stack.append(result)
stack.append(sign)
result = 0
sign = 1
elif ch == ')':
result += sign * num
num = 0
result *= stack.pop()
result += stack.pop()
return result + sign * numJavaTested in our runner
import java.util.*;
class Solution {
public int calculate(String s) {
Deque<Integer> saved = new ArrayDeque<>();
int result = 0;
int sign = 1;
int num = 0;
for (int i = 0; i < s.length(); i++) {
char ch = s.charAt(i);
if (Character.isDigit(ch)) {
num = num * 10 + (ch - '0');
} else if (ch == '+') {
result += sign * num;
num = 0;
sign = 1;
} else if (ch == '-') {
result += sign * num;
num = 0;
sign = -1;
} else if (ch == '(') {
saved.push(result);
saved.push(sign);
result = 0;
sign = 1;
} else if (ch == ')') {
result += sign * num;
num = 0;
result *= saved.pop();
result += saved.pop();
}
}
return result + sign * num;
}
}C++Tested in our runner
#include <stack>
#include <string>
using namespace std;
class Solution {
public:
int calculate(string s) {
stack<int> saved; // result is pushed first, then sign
int result = 0;
int sign = 1;
int num = 0;
for (char ch : s) {
if (ch >= '0' && ch <= '9') {
num = num * 10 + (ch - '0');
} else if (ch == '+') {
result += sign * num;
num = 0;
sign = 1;
} else if (ch == '-') {
result += sign * num;
num = 0;
sign = -1;
} else if (ch == '(') {
saved.push(result);
saved.push(sign);
result = 0;
sign = 1;
} else if (ch == ')') {
result += sign * num;
num = 0;
result *= saved.top();
saved.pop();
result += saved.top();
saved.pop();
}
}
return result + sign * num;
}
};JavaScriptTested in our runner
var calculate = function(s) {
const stack = [];
let result = 0;
let sign = 1;
let num = 0;
for (const ch of s) {
if (ch >= '0' && ch <= '9') {
num = num * 10 + (ch.charCodeAt(0) - 48);
} else if (ch === '+') {
result += sign * num;
num = 0;
sign = 1;
} else if (ch === '-') {
result += sign * num;
num = 0;
sign = -1;
} else if (ch === '(') {
stack.push(result);
stack.push(sign);
result = 0;
sign = 1;
} else if (ch === ')') {
result += sign * num;
num = 0;
result *= stack.pop();
result += stack.pop();
}
}
return result + sign * num;
};GoTested in our runner
func calculate(s string) int {
var saved []int // pairs: result, then sign
result := 0
sign := 1
num := 0
for i := 0; i < len(s); i++ {
ch := s[i]
if ch >= '0' && ch <= '9' {
num = num*10 + int(ch-'0')
} else if ch == '+' {
result += sign * num
num = 0
sign = 1
} else if ch == '-' {
result += sign * num
num = 0
sign = -1
} else if ch == '(' {
saved = append(saved, result, sign)
result = 0
sign = 1
} else if ch == ')' {
result += sign * num
num = 0
top := saved[len(saved)-1]
saved = saved[:len(saved)-1]
result *= top
prev := saved[len(saved)-1]
saved = saved[:len(saved)-1]
result += prev
}
}
return result + sign*num
}C#Tested in our runner
public class Solution {
public int calculate(string s) {
var saved = new Stack<int>();
int result = 0;
int sign = 1;
int num = 0;
foreach (char ch in s) {
if (ch >= '0' && ch <= '9') {
num = num * 10 + (ch - '0');
} else if (ch == '+') {
result += sign * num;
num = 0;
sign = 1;
} else if (ch == '-') {
result += sign * num;
num = 0;
sign = -1;
} else if (ch == '(') {
saved.Push(result);
saved.Push(sign);
result = 0;
sign = 1;
} else if (ch == ')') {
result += sign * num;
num = 0;
result *= saved.Pop();
result += saved.Pop();
}
}
return result + sign * num;
}
}Common mistakes
result += sign * digitinside the digit branch. This adds each digit as its own term, so12becomes 1 + 2. Only addsign * numwhen an operator or)ends the number, and buildnum = num * 10 + digiton each digit.- Skipping the flush before
). Callingresult *= stack.pop()directly drops the last number, such as the3in(2+3). Addsign * numand setnumto 0 before any pop. - Popping the result before the sign. The stack holds the result first and the sign second, so the sign is on top. Pop the sign for the multiply, then pop the result for the add.
- Forgetting to reset
resultandsignat(. The inner group then starts from the outer total, so2-(3)gives the wrong answer. Push both values, then setresult = 0andsign = 1. - Dropping the saved sign. Writing
result += saved_resultwithout multiplying by the saved sign loses the minus in-(2+3). The popped sign must multiply the group before the outer result is added. - Building
numwithout the* 10step, so123is read as separate digits. Each digit must multiply the running number by 10 before it adds the new digit.
Edge cases
1: no operator and no parenthesis. The final flush returns 1.-2 + 1: a leading minus sets the sign to -1 before the first number. The expected output is -1.(1): a group with one number and no operator. The expected output is 1.2-(5-6): a minus in front of a group that contains a minus. The expected output is 3.((((1)))): deep nesting. Each(pushes two values, so the stack reaches 8 entries and unwinds back to empty.2-1 + 2: leading, trailing and inner spaces are skipped. The expected output is 3.
Follow-ups interviewers ask
- What if the expression also had
*and/? - Keep the same stack for parentheses, and add a
termvariable that holds the most recent product or quotient. On*or/, combine the next number withterminstead of adding it toresult. Java, C++, C# and Go truncate integer division toward zero, while Python's//floors, so match the rule your interviewer expects. - Can you use recursion instead of an explicit stack?
- Yes. Write a function that reads from a shared index, calls itself on
(to evaluate the group, and returns the group's value on). The call stack then plays the role of the explicit stack. Python's default recursion limit is about 1000, so inputs with deep nesting need the iterative version. - Can you do it in O(1) extra space?
- Not with this method, because each open parenthesis needs a saved total and sign, and nesting can reach about n / 2. I am not aware of an O(1) extra space method that keeps O(n) time, so the stack is the answer to give in an interview.
Basic Calculator FAQ
What is the time complexity of Basic Calculator?
The one-pass stack solution runs in O(n) time, where n is the length of the string. Each character is handled once with constant work. The brute force that rebuilds the string after each group takes O(n^2) time.
Why use a stack for Basic Calculator?
Each ( suspends the outer total and sign, and each ) restores them. Groups close in the reverse order they open, which is the order a stack returns items. That match is why the stack handles nesting with one pass.
Can Basic Calculator be solved in O(1) extra space?
Not with the stack method, because each open parenthesis needs a saved total and sign, and nesting can reach about n / 2. I am not aware of an O(1) extra space method that keeps O(n) time, so the stack is the standard answer.
How does Basic Calculator handle a minus sign in front of a parenthesis?
The - sets sign to -1 before the (. The ( pushes that sign with the outer total, and the matching ) multiplies the group by it. So -(2+3) evaluates to -5.
Why does the string replacement method fail for Basic Calculator?
It rebuilds and rescans the whole string once per group. With up to 3 * 10^5 characters and deep nesting, the worst case reaches tens of billions of character operations, which is too slow.
Asked at
See which companies ask this — Pro
Related problems
- Basic Calculator III · same technique: Expression Evaluation (RPN/Infix)
- Evaluate Reverse Polish Notation · same technique: Expression Evaluation (RPN/Infix)
- Basic Calculator II · same technique: Expression Evaluation (RPN/Infix)
- Largest Rectangle in Histogram · same pattern: Stack Patterns
- Reconstruct Itinerary · same pattern: Stack Patterns
- Maximum Frequency Stack · same pattern: Stack Patterns
- Longest Valid Parentheses · same pattern: Stack Patterns
- Maximal Rectangle · same pattern: Stack Patterns
- Min Stack · same pattern: Stack Patterns
- Daily Temperatures · same pattern: Stack Patterns