All problems
0174HardMathStringStackRecursion

Bracketed Offset Total

Tracked in this browser only
Write code

Trains the technique from

LeetCode 224Basic Calculator

This is an original problem, written from a brief that listed the technique, the difficulty, the topics, the function shape and the input bounds — none of that problem's wording, examples, hints or editorials. The link is there so you can map your practice onto the standard set.

Same function shape, different story and different numbers.

A surveyor's notebook records how much a benchmark has moved as one long offset line, for example 40-(6+9). The line is a string expr built only from digits, +, -, round brackets and spaces.

Reading rules for the line:

  • + and - between two pieces add and subtract, applied left to right.
  • A bracketed group is read on its own, and whatever sits in front of the group applies to its whole value.
  • - may also appear as a sign in front of a single number or a bracketed group, as in -7 or -(4+2). + is never used that way.
  • Spaces carry no meaning.

Return the total offset the line describes. Passing the line to a language-provided expression evaluator is not allowed.

Examples

Example 1

Input
expr = "7 - (2 + 9)"
Output
-4

The bracketed group is worth 11, and the minus in front of it applies to all of it, so the line reads 7 - 11.

Example 2

Input
expr = "-(6-11)+4"
Output
9

The group is worth -5, the leading sign flips it to 5, and the trailing 4 brings the total to 9.

Example 3

Input
expr = "((3+12)-(5-1))-8"
Output
3

The inner groups are 15 and 4, so the outer group is 11, and subtracting 8 leaves 3.

Constraints

  • 1 <= expr.length <= 3 * 10^5
  • expr holds only digits, '+', '-', '(', ')' and ' '
  • expr is always a well-formed offset line
  • '+' never appears as a sign in front of a number or a group
  • '-' may appear as a sign in front of a number or a group
  • Two operators never sit next to each other
  • Every number and every running total fits in a signed 32-bit integer

The signature

The editor is preloaded with this. It matches the parent problem's shape, so a solution that works here transfers to a judge unchanged.

Python
def evaluate_offsets(expr: str) -> int:
Java
public int evaluateOffsets(String expr)
September 7
Apply