SDE & MLE Prep

224. Basic Calculator

Problem

Evaluate the expression s containing non-negative integers, +, -, parentheses and spaces, without eval. - can also be unary (as in -(2+3)), but never directly after another operator.

Example: "(1+(4+5+2)-3)+(6+8)" → 23

Constraints: length ≤ 3·10⁵.

Only + - ( ). Keep running res and sign. On (, push (res, sign) and restart; on ), res = saved_res + saved_sign * res.

Complexity: O(n).

class Solution:
    def calculate(self, s: str) -> int:
        res, num, sign, st = 0, 0, 1, []
        for ch in s:
            if ch.isdigit():
                num = num * 10 + int(ch)
            elif ch in "+-":
                res += sign * num
                num, sign = 0, (1 if ch == "+" else -1)
            elif ch == "(":
                st.append((res, sign))
                res, sign = 0, 1
            elif ch == ")":
                res += sign * num
                num = 0
                prev, psign = st.pop()
                res = prev + psign * res
        return res + sign * num