sagelearnai

Basic Calculator

Difficulty: Hard · Pattern: Stack & Monotonic Stack · LeetCode #224

Evaluate an expression with non-negative integers, +, − (including unary minus, as in -(2+3)), parentheses and spaces. Don't use eval.

Examples

text
"1 + 1"                →  2
" 2-1 + 2 "            →  3
"(1+(4+5+2)-3)+(6+8)"  →  23
"-(2+3)"               →  −5

Hints

  1. Without parentheses, keep a running result and the sign of the next number.
  2. At (, save the current result and sign on a stack and start fresh.
  3. At ), combine: saved_result + saved_sign × inner_result.

Approach

Maintain result, num and sign (±1). Digits build num. On + or −: add sign·num to result, reset num, and set sign. On (: push result and sign, then reset result = 0, sign = 1. On ): finish the inner expression (result += sign·num), then result = popped_result + popped_sign·result. At the end, add the last sign·num. O(n).

Complexity

Time: O(n). Space: O(nesting depth).

Python solution
def calculate(s):
    result, num, sign, st = 0, 0, 1, []
    for ch in s:
        if ch.isdigit():
            num = num * 10 + int(ch)
        elif ch in "+-":
            result += sign * num; num = 0
            sign = 1 if ch == "+" else -1
        elif ch == "(":
            st.append(result); st.append(sign)
            result, sign = 0, 1
        elif ch == ")":
            result += sign * num; num = 0
            prev_sign = st.pop(); prev = st.pop()
            result = prev + prev_sign * result
    return result + sign * num
JavaScript solution
function calculate(s) {
  let result = 0, num = 0, sign = 1; const st = [];
  for (const ch of s) {
    if (ch >= '0' && ch <= '9') num = num * 10 + Number(ch);
    else if (ch === '+' || ch === '-') { result += sign * num; num = 0; sign = ch === '+' ? 1 : -1; }
    else if (ch === '(') { st.push(result, sign); result = 0; sign = 1; }
    else if (ch === ')') { result += sign * num; num = 0; const ps = st.pop(), pr = st.pop(); result = pr + ps * result; }
  }
  return result + sign * num;
}