DSA Stacks

Basic Calculator

Evaluate expressions with +, -, and parentheses by tracking a running sign through a stack of suspended sums.

Hard
Time O(n) Space O(n)
LeetCode
5 min read
stack parsing

Problem#

Implement a calculator for an expression string containing digits, +, -, (, ), and spaces. No multiplication, division, or unary functions. Return the integer result.

Examples#

  • "1 + 1"2
  • " 2-1 + 2 "3
  • "(1+(4+5+2)-3)+(6+8)"23

Constraints#

  • 1 <= s.length <= 3 * 10^5. The expression is always valid.

Approach#

Sweep the string. Maintain result (running sum) and sign (+1 or -1 to apply to the next number). On (, push (result, sign) and reset. On ), pop (savedResult, savedSign) and update result = savedResult + savedSign * result. Read multi-digit numbers, applying the current sign.

Solution#

Basic Calculator
class Solution {
public:
int calculate(string s) {
stack<pair<int,int>> st;
long result = 0;
int sign = 1;
int i = 0, n = s.size();
while (i < n) {
char c = s[i];
if (isdigit(c)) {
long num = 0;
while (i < n && isdigit(s[i])) {
num = num * 10 + (s[i] - '0');
++i;
}
result += sign * num;
continue;
}
if (c == '+') sign = 1;
else if (c == '-') sign = -1;
else if (c == '(') {
st.push({(int)result, sign});
result = 0; sign = 1;
} else if (c == ')') {
auto [savedRes, savedSign] = st.top(); st.pop();
result = savedRes + savedSign * result;
}
++i;
}
return (int)result;
}
};

Editorial#

The stack stores the outer context that should be combined with the inner sub-expression’s result. Because there’s no * or /, sign tracking suffices — we always know whether the next number adds or subtracts. Numbers can be multi-digit, so we accumulate inside the digit loop.

Complexity#

  • Time: O(n).
  • Space: O(n) for stack depth.

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.