Problem
Evaluate a valid infix expression that contains non-negative integers, the operators + and -, empty spaces, and parentheses.
Original: LeetCode 224: Basic Calculator.
Examples
Example 1
`s = "1 + 1"``2`Example 2
`s = " 2-1 + 2 "``3`Example 3
`s = "(1+(4+5+2)-3)+(6+8)"``23`Constraints
1 <= s.length <= 3 * 10^5sconsists of digits,'+','-','(',')', and' '.srepresents a valid expression.'+'is not used as a unary operation (i.e.,"+1"and"+(2 + 3)"is invalid).'-'could be used as a unary operation (i.e.,"-1"and"-(2 + 3)"is valid).- There will be no two consecutive operators in the input.
- Every number and running calculation will fit in a signed 32-bit integer.
Hints
Hint 1
There is no multiplication or division here. Parentheses can nest. Unary minus appears as subtraction, including cases such as "-(2+3)" or "1-( -2 )" depending on spacing, but the official input uses binary operators and parentheses around groups.
Hint 2
An infix expression with parentheses is a stack of pending results and signs: the opening parenthesis saves the outer context, and the closing parenthesis finishes the inner sum and applies the saved sign.
Solution
Tried it yourself? The approach, complexity, and code stay hidden until you choose.
Approach
Brute force. Finding matching parentheses and evaluating from the inside out is correct but repeatedly scans the same characters.
Optimal. One left-to-right pass: accumulate a number, add sign * number into result on each operator, and use a stack only for parentheses.
Alternative. Convert to reverse Polish notation with a shunting-yard stack, then evaluate. That is the same work when more operators appear.
Complexity
- Time
- O(n)
O(n) time and O(n) space in the worst case of nested parentheses.
- Space
- O(n)
Code
def calculate(s: str) -> int:
stack: list[int] = []
result, number, sign = 0, 0, 1
for c in s:
if c.isdigit():
number = number * 10 + int(c)
elif c in "+-":
result += sign * number
number = 0
sign = 1 if c == "+" else -1
elif c == "(":
stack.append(result)
stack.append(sign)
result, sign = 0, 1
elif c == ")":
result += sign * number
number = 0
result *= stack.pop()
result += stack.pop()
sign = 1
return result + sign * number
if __name__ == "__main__":
assert calculate("1 + 1") == 2
assert calculate(" 2-1 + 2 ") == 3
assert calculate("(1+(4+5+2)-3)+(6+8)") == 23
print("ok")import java.util.ArrayDeque;
public class BasicCalculator {
static int calculate(String s) {
var stack = new ArrayDeque<Integer>();
int result = 0, number = 0, sign = 1;
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (Character.isDigit(c)) {
number = number * 10 + (c - '0');
} else if (c == '+' || c == '-') {
result += sign * number;
number = 0;
sign = c == '+' ? 1 : -1;
} else if (c == '(') {
stack.addLast(result);
stack.addLast(sign);
result = 0;
sign = 1;
} else if (c == ')') {
result += sign * number;
number = 0;
result *= stack.removeLast();
result += stack.removeLast();
sign = 1;
}
}
return result + sign * number;
}
public static void main(String[] args) {
if (calculate("1 + 1") != 2) throw new AssertionError();
if (calculate(" 2-1 + 2 ") != 3) throw new AssertionError();
if (calculate("(1+(4+5+2)-3)+(6+8)") != 23) throw new AssertionError();
System.out.println("ok");
}
}Edge cases
- Official samples: "1 + 1" equals 2, " 2-1 + 2 " equals 3, and "(1+(4+5+2)-3)+(6+8)" equals 23.
- Spaces are ignored. Multi-digit numbers must be accumulated.
- After a closing parenthesis, commit the inner number before combining with the saved sign and result.
Follow-ups
- Basic Calculator II adds * and / but drops parentheses.
- Basic Calculator III combines both.
Interview script
"I keep a running result and the sign in front of the current number. When I see an opening parenthesis I push the result and the sign, and I start a new result at zero. A closing parenthesis finishes the inner sum, multiplies it by the saved sign, and adds the saved result."
Source: LeetCode 224: Basic Calculator
Sources (1)
- LeetCode 224: Basic Calculatorleetcode.com