Basic Calculator

Hard

Topics
MathStringStack

Given a string s representing a valid expression, implement a basic calculator to evaluate it and return the result. The expression contains non-negative integers, +, -, (, ), spaces, and unary minus.

Example 1

10 1+2 314
Only +, - and brackets, so no precedence — but a leading - before a bracket flips the sign of everything inside it. Pushing the running total and the current sign at (, and folding back at ), handles arbitrary nesting. Result: 2.
Cells are the characters of the string; the small numbers underneath are indices.
Input:  s = "1 + 1"
Output: 2

Example 2

021-213 4+5 627 8
Input:  s = " 2-1 + 2 "
Output: 3

Example 3

(011+2(344+556+728)9-10311)12+13(14615+16817)18
bracket
Input:  s = "(1+(4+5+2)-3)+(6+8)"
Output: 23

Constraints

  • 1 <= s.length <= 20
  • s consists of digits, '+', '-', '(', ')', and spaces.
  • s represents a valid expression.
Editorial — intuition, approach, complexity and pitfalls

Intuition

The textbook answer is to parse: tokenise, build a tree or convert to postfix with the shunting-yard algorithm, then evaluate. That works and is the right tool when there are many operators with different precedences. Here it is heavier than the problem needs.

What makes a shortcut available is the restricted grammar: only +, -, parentheses and non-negative integers. There is no multiplication, so there is no precedence to resolve — the expression can be evaluated strictly left to right. That removes the only reason to build a tree.

Without precedence, every number in the whole expression contributes to the final answer with either a + or a - in front of it, and the parentheses only serve to flip signs. 1 - (2 - 3) is just 1 - 2 + 3. So we can sweep once, keeping a running total and the sign that applies to the next number.

The only thing a parenthesis changes is that the result inside must be computed independently and then folded in with the sign that preceded it. That is a save-and-restore, which is exactly a stack:

  • On (, push the result accumulated so far and the sign sitting in front of the bracket, then reset both to start a fresh sub-expression.
  • On ), close out the sub-expression, multiply it by the saved sign, and add the saved outer result back.

Note what is not on the stack: operators, tokens, or sub-expression trees. Only two integers per nesting level. The structure is a running total plus a sign, and the stack is there to remember suspended ones.

Approach

  1. Keep num (digits being accumulated), sign (+1 or -1, applying to the next number), and result (the running total at this nesting level).
  2. On a digit, extend num with num * 10 + digit — numbers are multi-digit, so they cannot be read one character at a time.
  3. On + or -, commit the pending number with result += sign * num, reset num to 0, and set sign.
  4. On (, push result then sign, and reset both. The push order matters only in that the pop order must mirror it.
  5. On ), commit the pending number, then result = result * popped_sign + popped_result.
  6. After the loop, commit the final pending number: result + sign * num. Nothing else flushes it, since the expression does not end in an operator.

Spaces need no handling at all — none of the branches match them, so they are skipped naturally.

Dry Run

s = "(1+(4+5+2)-3)+(6+8)", expected 23.

ch    action                                              result  sign  stack
(     push result,sign; reset                                  0    +1   [0,1]
1     num=1
+     commit: result += +1*1                                   1    +1   [0,1]
(     push result,sign; reset                                  0    +1   [0,1,1,1]
4     num=4
+     commit: result += +1*4                                   4    +1   [0,1,1,1]
5     num=5
+     commit: result += +1*5                                   9    +1   [0,1,1,1]
2     num=2
)     commit -> 11, then 11*pop(1) + pop(1) = 12              12    +1   [0,1]
-     sign = -1                                               12    -1   [0,1]
3     num=3
)     commit -> 12-3 = 9, then 9*pop(1) + pop(0) = 9           9    -1   []
+     sign = +1                                                9    +1   []
(     push result,sign; reset                                  0    +1   [9,1]
6     num=6
+     commit: result += +1*6                                    6   +1   [9,1]
8     num=8
)     commit -> 14, then 14*pop(1) + pop(9) = 23              23    +1   []

end   result + sign*num = 23 + 0 = 23

The step to study is the first ) at the inner bracket: result is the value of 4+5+2 alone, because ( reset it, and the saved 1 is what the outer level had accumulated. Folding is multiply-then-add, in that order — the sign applies to the bracket's value, not to the outer total.

Complexity

  • Time — O(n): one pass, constant work per character. Same as shunting-yard, but with no token list and no second evaluation pass.
  • Space — O(n): the stack holds two integers per open parenthesis, so it is O(d) in nesting depth d, which is O(n) in the worst case of ((((...)))). Notably this is not O(n) in the number of tokens — a long flat expression like 1+2+3+...+1000 uses no stack at all.

Common Pitfalls

  • Reading digits one character at a time. Inputs contain multi-digit numbers, so num = num * 10 + d is required; treating "42" as 4 then 2 is the most common failure.
  • Forgetting the final commit after the loop. The last number is still pending in num when the string ends, so returning result alone drops it.
  • Popping in the wrong order. Push is result-then-sign, so pop must be sign-then-result; swapping them silently corrupts every nested expression.
  • Adding before multiplying on ). The saved sign multiplies the bracket's value; applying it to the sum of bracket and outer result gives the wrong sign on the outer part.
  • Not resetting sign to +1 after (. A leading - outside a bracket would otherwise leak into the first term inside it.
  • Assuming unary minus cannot appear. Expressions like -(3+4) or (-2+1) work with this scheme because sign starts at +1 and num at 0, so a leading - commits a harmless +1*0 and then sets the sign — worth checking rather than assuming.
  • Reaching for a full expression parser. Correct, but it is far more code than a problem without precedence requires, and the follow-up (add * and /) is better answered by extending this scan than by having started with shunting-yard.

Full Solution — all languages

class Solution:
    def calculate(self, s):
        stack = []
        num = 0
        sign = 1
        res = 0
        for c in s:
            if c.isdigit():
                num = num * 10 + int(c)
            elif c == '+':
                res += sign * num
                num = 0
                sign = 1
            elif c == '-':
                res += sign * num
                num = 0
                sign = -1
            elif c == '(':
                stack.append(res)
                stack.append(sign)
                res = 0
                sign = 1
            elif c == ')':
                res += sign * num
                num = 0
                res *= stack.pop()
                res += stack.pop()
        res += sign * num
        return res
SensAI
Beta
Tap the mic to stop voice mode