05. Basic Calculator

Difficulty:HardPattern:Stack Math Expression ParserTime:O(n)Space:O(n)

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:

  1. Variables: sum = 0, sign = 1, stack = [].
  2. Scan String:
    • Digit: parse complete number $N$, update sum += sign * N.
    • Operator +: set sign = 1.
    • Operator -: set sign = -1.
    • Open Parenthesis '(': push current sum and sign onto stack, reset sum = 0, sign = 1.
    • Close Parenthesis ')': pop prevSign and prevSum from stack; set sum = prevSum + prevSign * sum.

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.