KatInterview

Evaluate Nested Arithmetic Brackets with Sign Propagation

Stacks & QueuesAuto-graded · 19 test cases
MediumAuto-gradedStacks & Queuesstacksexpression evaluationparsing

Last 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 = 0
  • 3-(2-1) → 3 - (2-1) = 3 - 1 = 2
  • -(3+2) → -5
  • 1+(-(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.