LeetCode #224 Hard

Basic Calculator

Basic Calculator is LeetCode 224 (Hard). Given a string s holding a valid expression, return its value. You may not use a built-in evaluator such as eval().

  • The expression has non-negative integers, +, -, (, ) and spaces. There is no * or /.
  • - can be unary, as in -1 or -(2 + 3); + never is.
  • s can be 3 · 10⁵ characters long, so the answer has to come from one linear pass.
Constraints
  • 1 <= s.length <= 3 * 10⁵
  • s consists of digits, '+', '-', '(', ')', and ' '.
  • s represents a valid expression.
  • '+' is not used as a unary operation ("+1" and "+(2 + 3)" are invalid).
  • '-' could be used as a unary operation ("-1" and "-(2 + 3)" are valid).
  • There will be no two consecutive operators in the input.
  • Every number and running calculation will fit in a signed 32-bit integer.
stackmathstrings
Open on LeetCode ↗
02

Intuition

With only + and -, every number is simply added with a sign: 5 - 3 + 2 is +5, -3, +2. So one scan with a running result and the sign for the next number does all the work.

Brackets are the one complication, because a - in front of a group flips every number inside it. At (, save the outer result and the sign in front of the group, then evaluate the inside from zero. At ), multiply the inside's total by that saved sign and add the saved result back. A stack holds the saved pairs, so groups can nest to any depth.

How to spot this pattern

An expression with brackets but only one level of operator strength needs a stack of saved contexts, not an operator-precedence parser. Decode String has the same shape: save the outer state at the opening bracket and merge it back at the closing one.

03

Approach

Try it first

Before reading on, evaluate 2 - (5 - 6) by hand, left to right, and write down what you had to remember at the moment you reached (. Aim for one O(n) pass.

1

Build each number digit by digit

On a digit, set num = num * 10 + digit. A number can span several characters, so it is only complete when a non-digit arrives. Spaces match no branch and are skipped for free.

2

Add the number when an operator ends it

On + or -, add sign * num to result, reset num to 0, and set sign to 1 or -1 for the number that comes next. Subtraction becomes adding a negative, so there is only one kind of update.

3

Save the outer level at an opening bracket

On (, push result, then push sign, and reset them to 0 and 1. The group is a fresh expression of its own, and the pushed sign is the one written in front of the bracket, so it applies to the whole group.

4

Fold the group back in at a closing bracket

On ), first add the group's last number with result += sign * num. Then result *= stack.pop() applies the saved sign, and result += stack.pop() adds the saved outer total. The pops come in the reverse of the push order: sign first, then total.

5

Add the final number

After the loop, return result + sign * num. The last number in the string has no operator after it, so nothing inside the loop has added it yet.

04

Code in Python, C++ and Java

▶1class Solution:
▶2 def calculate(self, s):
▶3 stack = []
▶4 result, sign, num = 0, 1, 0
▶5 for ch in s:
▶6 if ch.isdigit():
▶7 num = num * 10 + int(ch)
▶8 elif ch in "+-":
▶9 result += sign * num
▶10 num = 0
▶11 sign = 1 if ch == "+" else -1
▶12 elif ch == "(":
▶13 stack.append(result)
▶14 stack.append(sign)
▶15 result, sign = 0, 1
▶16 elif ch == ")":
▶17 result += sign * num
▶18 num = 0
▶19 result *= stack.pop()
▶20 result += stack.pop()
▶21 return result + sign * num
expression2−(5−6)this level0total+next sign2numberdepth0saved levels (stack)emptydigit 2 → number 2
total0
sign1
number2
depth0
A digit starts a number. It is not added yet, because more digits may follow.
expression2−(5−6)this level2total−next signnumberdepth0saved levels (stack)emptyadd 2 → total 2, next sign −
total2
sign-1
numbernone
depth0
The minus ends the number 2. It is added with its sign: 0 + 2 = 2. The next number gets sign −.
expression2−(5−6)this level0total+next signnumberdepth1saved levels (stack)2−totalsigntopsave total 2 and sign − → start inside at 0
total0
sign1
numbernone
depth1
A group starts. Its value is not known yet, so save the outer total 2 and the sign in front of the bracket (−), then evaluate the inside as a fresh expression from total 0, sign +. That saved minus will flip the whole group.
expression2−(5−6)this level0total+next sign5numberdepth1saved levels (stack)2−totalsigntopdigit 5 → number 5
total0
sign1
number5
depth1
A digit starts a number. It is not added yet, because more digits may follow.
expression2−(5−6)this level5total−next signnumberdepth1saved levels (stack)2−totalsigntopadd 5 → total 5, next sign −
total5
sign-1
numbernone
depth1
The minus ends the number 5. It is added with its sign: 0 + 5 = 5. The next number gets sign −.
expression2−(5−6)this level5total−next sign6numberdepth1saved levels (stack)2−totalsigntopdigit 6 → number 6
total5
sign-1
number6
depth1
A digit starts a number. It is not added yet, because more digits may follow.
expression2−(5−6)this level3total+next signnumberdepth0saved levels (stack)emptygroup is −1, saved 2 − → total 3
total3
sign1
numbernone
depth0
First the last number inside, 6, is added, so the group's value is −1. Pop the saved level: sign −, then total 2. The group is folded back in as 2 − (−1) = 3.
expression2−(5−6)this level3total+next signnumberdepth0saved levels (stack)emptyend of string → answer 3
answer3
The string ends on a bracket, so no number is waiting. The total, 3, is the answer.
05

Common pitfalls

Dropping the last number

✗ Wrong
return result
✓ Right
return result + sign * num

Numbers are only added when an operator or ) follows them, and the last number has neither. "1 + 2" returns 1.

Popping the saved pair in push order

✗ Wrong
outer = stack.pop()
saved_sign = stack.pop()
result = outer + saved_sign * result
✓ Right
result *= stack.pop()
result += stack.pop()

The total was pushed first and the sign second, so the sign comes off first. Reading them the other way round treats the sign as the total. "5 - (2)" returns 9 instead of 3.

Closing a group before adding its last number

✗ Wrong
elif ch == ")":
    result *= stack.pop()
    result += stack.pop()
✓ Right
elif ch == ")":
    result += sign * num
    num = 0
    result *= stack.pop()
    result += stack.pop()

The number just before ) is still waiting in num, so the saved sign never reaches it, and it is added later with the wrong sign. "-(1 + 2)" returns 1 instead of -3.

06

Edge cases

Unary minus, at the start or right after (

result starts at 0, so -(2 + 3) is read as 0 - (2 + 3): the - adds 1 * 0 and sets the sign to -1. Inside a group the reset to 0 does the same job, so 1 - (-2) gives 3.

07

Complexity

Time
O(n)
Space
O(n)
n is the length of s. Each character is handled once with O(1) work. The stack holds two entries per open bracket, so it grows to O(n) only when brackets nest deeply.
08

Basic Calculator FAQ

How is the version with * and / different?

Basic Calculator II has * and / but no brackets, so the hard part moves from nesting to precedence. Its stack holds terms waiting to be summed, and * or / merges into the top term at once. Here the stack holds saved outer levels instead. Basic Calculator III combines both: brackets and all four operators.

Can I solve it with recursion instead of a stack?

Yes. At (, call the same function on the rest of the string and have it return its value and the index of the matching ). It is O(n) too, but one call per nesting level means very deep brackets overflow Python's recursion limit, which the stack version never hits.