Practice › Stack & Queue
Basic Calculator with Parentheses
Hard · Stack & Queue · Asked at Google, Amazon, Meta, Microsoft, Uber
Evaluate an expression with non-negative integers, +, -, parentheses and spaces. A - may also be unary — at the very start, or right after ( — as in -(2+3). Print the result.
Input
A single line with the expression (always valid).
Output
The value of the expression.
Constraints
- 1 ≤ length ≤ 10^5
- every intermediate result fits in a signed 64-bit integer
Scan left to right with a running result and the current sign. On
(, push the result and the sign that applies to the bracket, then start fresh; on), finish the inner result and combine: result = pushedResult + pushedSign × inner. A unary minus works naturally because the result before it is 0.
Example 1
Input
1 + 1
Output
2
Example 2
Input
2-1 + 2
Output
3
Example 3
Input
(1+(4+5+2)-3)+(6+8)
Output
23
Hints
- Without parentheses you only need a running result and the sign of the next number.
- A "(" starts a fresh sub-expression; remember the result so far and the sign in front of the bracket.
- A unary minus behaves like "0 − …" because the result before it is 0.
Approach
Scan with result, sign (+1 or −1) and the number being read. On + or −, add sign × number to result and set the new sign. On "(", push result and sign onto a stack, then reset result = 0, sign = +1. On ")", finish the inner result, pop the saved sign and result, and set result = savedResult + savedSign × inner. A leading "-" or one right after "(" just sets sign = −1 for the next value, which is exactly unary minus. Use 64-bit integers.
Complexity: O(n) time · O(depth) space
Solution
C++ solution
#include <bits/stdc++.h>
using namespace std;
int main() {
string s;
getline(cin, s);
long long result = 0, num = 0;
int sign = 1;
vector<long long> st;
for (char c : s) {
if (isdigit((unsigned char) c)) num = num * 10 + (c - '0');
else if (c == '+' || c == '-') {
result += sign * num;
num = 0;
sign = c == '+' ? 1 : -1;
} else if (c == '(') {
st.push_back(result);
st.push_back(sign);
result = 0;
sign = 1;
} else if (c == ')') {
result += sign * num;
num = 0;
long long savedSign = st.back();
st.pop_back();
long long savedResult = st.back();
st.pop_back();
result = savedResult + savedSign * result;
}
}
cout << result + sign * num << "\n";
return 0;
}Python solution
import sys
s = sys.stdin.readline()
result = num = 0
sign = 1
stack = []
for c in s:
if c.isdigit():
num = num * 10 + ord(c) - 48
elif c in "+-":
result += sign * num
num = 0
sign = 1 if c == "+" else -1
elif c == "(":
stack.append(result)
stack.append(sign)
result, sign = 0, 1
elif c == ")":
result += sign * num
num = 0
saved_sign = stack.pop()
saved_result = stack.pop()
result = saved_result + saved_sign * result
print(result + sign * num)Java solution
import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws IOException {
String s = new BufferedReader(new InputStreamReader(System.in)).readLine();
long result = 0, num = 0;
int sign = 1;
ArrayDeque<Long> st = new ArrayDeque<>();
for (char c : s.toCharArray()) {
if (Character.isDigit(c)) num = num * 10 + (c - '0');
else if (c == '+' || c == '-') {
result += sign * num;
num = 0;
sign = c == '+' ? 1 : -1;
} else if (c == '(') {
st.push(result);
st.push((long) sign);
result = 0;
sign = 1;
} else if (c == ')') {
result += sign * num;
num = 0;
long savedSign = st.pop();
long savedResult = st.pop();
result = savedResult + savedSign * result;
}
}
System.out.println(result + sign * num);
}
}Solve Basic Calculator with Parentheses online · All practice problems