Basic Calculator (LeetCode 224): Solution and Explanation

Hard
Math
String
Stack
Recursion

Evaluate an arithmetic expression given as a string. It contains non-negative integers, plus and minus signs, parentheses and spaces, and a minus may also act as a unary negation. You must compute the result yourself without calling a built-in evaluator.

Variables
No variables to display
DepthFunction Call
Stack empty
0/0

Intuition

The textbook approach is to convert the expression to postfix with the shunting-yard algorithm and then evaluate it with a stack. That works for any operator set, but it is a lot of machinery for an expression that only has addition, subtraction and parentheses.

The simplification comes from noticing that with only plus and minus, every number ends up either added or subtracted from the total. If you know the effective sign in front of each number, you can just accumulate sign * num into a running result as you scan. Multi-digit numbers are built digit by digit, and each time you hit an operator you flush the current number into the result and remember the new sign.

Parentheses are the only thing that breaks this flat picture, because a minus in front of a group flips everything inside it. The fix is to treat a parenthesized group as a fresh sub-expression. When you see '(', you push the result so far and the sign that applies to the group onto a stack, then start a clean result of zero. When you see ')', you finish the inner result, multiply it by the saved sign, and add it to the saved outer result. Nested groups simply stack up, so one left-to-right pass handles any depth.

Approach: Single pass with a sign and a stack

  1. Initialize an empty stack, num = 0, sign = 1 and result = 0.
  2. For a digit, extend the current number with num = num * 10 + int(char).
  3. For '+' or '-', add sign * num to result, reset num to 0, and set sign to 1 or -1.
  4. For '(', push result and then sign, and reset both so the group is evaluated on its own.
  5. For ')', add the pending sign * num to result, reset num, multiply result by the popped sign, then add the popped outer result.
  6. Spaces fall through every branch and are ignored. At the end, return result + sign * num to flush the last number.

Step-by-step example

s = "2-(5-6)"
  1. Reading '2' sets num = 2. The '-' adds 2 to result, resets num and sets sign = -1.
  2. At '(' the stack becomes [2, -1], and result and sign reset to 0 and 1.
  3. Inside the group, '5' sets num = 5, then '-' makes result = 5 and sign = -1, and '6' sets num = 6.
  4. At ')' the inner result becomes 5 - 6 = -1. Multiplying by the popped sign -1 gives 1, and adding the popped 2 gives result = 3.
  5. The string ends with num = 0, so the function returns 3 + (-1 × 0) = 3.

Code: Python, Java, C++

1class Solution:
2    def calculate(self, s: str) -> int:
3        stack = []
4        num = 0
5        sign = 1
6        result = 0
7
8        for char in s:
9            if char.isdigit():
10                num = num * 10 + int(char)
11            elif char == '+':
12                result += sign * num
13                num = 0
14                sign = 1
15            elif char == '-':
16                result += sign * num
17                num = 0
18                sign = -1
19            elif char == '(':
20                stack.append(result)
21                stack.append(sign)
22                result = 0
23                sign = 1
24            elif char == ')':
25                result += sign * num
26                num = 0
27                result *= stack.pop()  # sign
28                result += stack.pop()  # previous result
29
30        return result + sign * num

Time and space complexity

Time

O(n)

Each character is processed once with constant work, and every push onto the stack is matched by exactly one pair of pops at the closing parenthesis.

Space

O(n)

The stack holds two values per open parenthesis, so deeply nested input such as many leading '(' characters uses space proportional to the string length.

Other approaches

Recursive descent (time O(n), space O(n))

Write a function that parses terms and calls itself when it sees '(', returning both the value and the index where the group ended. It mirrors the grammar directly and extends easily to multiplication, but uses the call stack instead of an explicit one.

Shunting-yard to postfix (time O(n), space O(n))

Convert the infix expression to postfix with an operator stack, then evaluate the postfix with a value stack. It is the general solution for many operators and precedences, but needs special handling for unary minus and is far more code than this problem requires.

Common mistakes

  • Forgetting to flush the final number. If the expression ends in a digit, num still holds it, which is why the return adds sign * num.
  • Treating each digit as its own number. You must accumulate multi-digit values with num * 10 + digit before applying the sign.
  • Pushing only the result at '(' and losing the sign in front of the group. Without the saved sign, an expression like '1-(2+3)' evaluates to 6 instead of -4.
  • Not resetting num after ')'. The inner number has already been applied, and leaving it set would add it a second time.

Frequently asked questions

How does Basic Calculator handle a unary minus?

A leading '-' or a '-' right after '(' is processed like any other minus: it adds the current num, which is 0, and sets sign = -1. The next number or group is then subtracted, which is exactly what unary negation means.

Why is a stack needed in Basic Calculator?

Parentheses create nested scopes. When a group closes, you need the result and sign that were in effect just before it opened, and a stack returns the most recently saved context first, which matches how parentheses nest.

What is the time complexity of Basic Calculator?

It is O(n), because the string is scanned once and each character costs constant time. The stack adds O(n) space only in the worst case of deep nesting.

How do I extend this to multiplication and division?

That is the Basic Calculator II and III family. You keep the last term separately so that '*' and '/' can bind to it before it is added to the total, and combine that with the same stack trick for parentheses.