You are given a string that represents a valid arithmetic expression built from non-negative integers, the operators plus and minus, parentheses, and spaces. A minus sign may act as a unary operator, and parentheses can be nested to any depth to group subexpressions.
Evaluate the expression and return its integer value. You must implement the evaluation yourself rather than relying on any built-in function that parses or executes expressions.
Spaces may appear anywhere and should be ignored, and the final result is guaranteed to fit in a 32-bit signed integer.
Example 1
Input: s = "1 + 1"
Output: 2
The two operands are added together after the spaces are ignored.
Example 2
Input: s = "(1+(4+5+2)-3)+(6+8)"
Output: 23
The inner group 4+5+2 is 11, so the first parenthesis gives 1+11-3 = 9, the second gives 14, and 9+14 = 23.
Constraints
1 <= s.length <= 3 * 10^5s consists of digits, '+', '-', '(', ')', and ' '.s represents a valid expression.The parentheses in s are always balanced.The answer is guaranteed to fit in a 32-bit integer.See the step-by-step animation, the intuition, and clean code in every language — free, no credit card.
FDE Coach is a cohort-based program in frontend, backend, AWS, and AI where you build real products and get referred to 200+ hiring partners. The free live workshop is the fastest way to see how we teach.
750+ engineers trained · frontend, backend, AWS & AI