Ctrl K

Plus-Minus Calculator With Brackets

Hard
The string expr is a valid arithmetic expression made of non-negative integers, the signs + and -, round brackets and spaces. Evaluate it and return the result. A minus may be unary: -7 and -(1 + 2) are allowed. A plus is never unary, and two signs never stand next to each other. Spaces may appear anywhere between numbers and signs. Do not use anything built in that evaluates a string as an expression (such as eval): parse the string yourself.
Example 1
expr="12 - (4 + 3) + 1" → 6

The bracket gives 7, then 12 - 7 + 1 = 6.

Example 2
expr="-(8 - (2 + 9))" → 3

Inside it is 8 - 11 = -3, and the minus in front of the bracket flips it to 3.

Example 3
expr=" 40 " → 40
Constraints
  • 1 ≤ len(expr) ≤ 10⁶
  • expr consists of digits, +, -, (, ) and spaces
  • expr is a valid expression
  • Every number, every bracket value and the result fit in a signed 32-bit integer
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsSimplify a Letter Polynomial HardCalculator With Brackets and Four Operations HardAmount in Words HardA Calculator With Brackets and Variables HardA Nested Logic Formula Hard
loading Python…
Input
expr="12 - (4 + 3) + 1"
Expected
6

Run checks the first 3 tests in your browser. Submit checks all 80 tests on the server, hidden ones included.