Evaluate Nested Arithmetic Brackets with Sign Propagation
Stacks & QueuesAuto-graded · 19 test casesLast updated
Tests expression evaluation using a monotonic/simulation stack to handle deeply nested signed bracket expressions with +/- operators and integer literals.
Evaluate Nested Arithmetic Brackets with Sign Propagation
You are given a string representing an arithmetic expression built from non-negative integer literals, the binary/unary operators + and -, and arbitrarily nested parentheses ( and ).
The expression follows these rules:
- A
-immediately after an opening(or at the very start of the string acts as a unary minus on everything that follows until the matching)closes (or the string ends). - Otherwise
+and-are standard left-to-right binary operators. - Parentheses may be nested to any depth.
- There are no spaces in the input string.
- The expression is always well-formed (balanced parentheses, no consecutive binary operators, no trailing operators).
Your task: compute and return the integer result of the expression.
How sign propagation works
When a ( is encountered, the current running sign is pushed onto a stack. If the character immediately following ( is -, the sign for the contents of that bracket group is flipped relative to the outer sign. A + after ( (or no explicit sign) leaves the sign unchanged.
For example:
3-(2+1)→3 - 3 = 03-(2-1)→3 - (2-1) = 3 - 1 = 2-(3+2)→-51+(-(2+3))→1 + (-5) = -4
Constraints
1 ≤ len(s) ≤ 2000- The string contains only digits
0–9,+,-,(,). - Integer literals are in the range
[0, 10^6]. - Parentheses are properly balanced.
- No spaces in the input.
- The expression is always well-formed.
- The result fits in a 32-bit signed integer.
Examples
Example 1
Input: evaluate_bracket_expression('3-(2+1)')
Output: 0
Example 2
Input: evaluate_bracket_expression('1+(-(2+3))')
Output: -4
Example 3
Input: evaluate_bracket_expression('10+2-(3-(4+1))')
Output: 14
Hints
Hint 1
Use a stack to track the 'accumulated result so far' and the 'effective sign' each time you enter a new parenthesised group.
Hint 2
When you see '(', push the current result and current sign onto the stack, then reset. When you see ')', pop and combine: result = popped_result + popped_sign * current_result.
Hint 3
Parse multi-digit numbers by accumulating digit characters before acting on an operator or bracket.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Key Insight
This is a classic stack-based expression evaluation problem. Instead of building an AST or using two separate stacks (operator + operand), we maintain:
result: the accumulated value of the current bracket level.sign: the effective multiplier (+1or-1) to apply to the next number parsed.stack: stores(result_so_far, sign_of_group)pairs whenever we descend into a(...).
Algorithm (single left-to-right pass)
- Digit — parse the full multi-digit integer, add
sign * numbertoresult. +— setsign = +1.-— setsign = -1.(— push(result, sign)onto the stack; resetresult = 0,sign = 1.)— pop(outer_result, outer_sign); combine:result = outer_result + outer_sign * result; resetsign = 1.
Why it is correct
- Every
(saves the "world outside the brackets" and starts fresh. - Every
)restores the outer world and folds in the inner sub-expression with the sign that was active at the moment the(was opened (which is exactly thesignvalue that was current when we entered). - A unary
-at the start of the string or after(is handled naturally: it simply setssign = -1before any number is consumed at that level.
Complexity
- Time: O(n) — each character is visited exactly once.
- Space: O(d) where d is the maximum nesting depth (stack size); O(n) worst case.
def evaluate_bracket_expression(s: str) -> int:
stack = [] # each entry: (result_so_far, sign_of_this_group)
result = 0
sign = 1 # current effective sign (+1 or -1)
i = 0
n = len(s)
while i < n:
ch = s[i]
if ch.isdigit():
# Parse full multi-digit number
j = i
while j < n and s[j].isdigit():
j += 1
result += sign * int(s[i:j])
i = j
continue
elif ch == '+':
sign = 1
elif ch == '-':
sign = -1
elif ch == '(':
# Push current state
stack.append((result, sign))
# Reset for the inner expression
result = 0
sign = 1
elif ch == ')':
# Combine inner result with outer
outer_result, outer_sign = stack.pop()
result = outer_result + outer_sign * result
# After closing a group, the next operator sets the sign;
# reset sign to +1 as a neutral default
sign = 1
i += 1
return result