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-1or-(2 + 3);+never is.scan be 3 · 10⁵ characters long, so the answer has to come from one linear pass.
- 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.
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.
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.
Approach
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.
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.
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.
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.
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.
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.
Code in Python, C++ and Java
Common pitfalls
Dropping the last number
return result
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
outer = stack.pop() saved_sign = stack.pop() result = outer + saved_sign * result
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
elif ch == ")":
result *= stack.pop()
result += stack.pop()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.
Edge cases
(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.
Complexity
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.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.