05. Basic Calculator
Given a string s representing a valid expression containing digits, '+', '-', '(', and ')', evaluate the expression and return its value.
How It Works & Algorithmic Design
Solves using Linear Scan Stack Parentheses State Preservation:
- Variables:
sum = 0,sign = 1,stack = []. - Scan String:
- Digit: parse complete number $N$, update
sum += sign * N. - Operator
+: setsign = 1. - Operator
-: setsign = -1. - Open Parenthesis
'(': push currentsumandsignonto stack, resetsum = 0,sign = 1. - Close Parenthesis
')': popprevSignandprevSumfrom stack; setsum = prevSum + prevSign * sum.
- Digit: parse complete number $N$, update
Why This Approach Works Best
Evaluates nested parenthesis expressions in a single pass $O(n)$ time and $O(n)$ stack space.
Example Walkthrough
Input
s = "(1+(4+5+2)-3)+(6+8)"
Nested math string.
Evaluation
(1+11-3) + 14 = 9 + 14 = 23
Evaluated calculation.
Output
23
Final computed integer.
Answer: Basic Calculator implementation
function calculate(s) {
let sum = 0, sign = 1;
const stack = [];
let i = 0;
while (i < s.length) {
const ch = s[i];
if (ch >= '0' && ch <= '9') {
let num = 0;
while (i < s.length && s[i] >= '0' && s[i] <= '9') {
num = num * 10 + Number(s[i++]);
}
sum += sign * num;
continue;
} else if (ch === '+') sign = 1;
else if (ch === '-') sign = -1;
else if (ch === '(') {
stack.push(sum);
stack.push(sign);
sum = 0; sign = 1;
} else if (ch === ')') {
sum = stack.pop() * sum + stack.pop();
}
i++;
}
return sum;
}Evaluate expressions linearly using a stack to preserve sum and sign context across parentheses.
Key Takeaways
Parentheses save scope state onto stack.
Handles nested expressions in $O(n)$ linear time.
Consumes minimal space bounded by depth of nested parentheses.