Skip to content
DeepForgeby svx
All problems
HardAlgorithmsal-301

Basic Calculator with Parentheses

Problem

Evaluate an expression string with non-negative integers, +, -, parentheses and spaces, where a minus sign may also precede an opening parenthesis or a number.

Use a stack to save the result and sign whenever an opening parenthesis appears, restart the running result inside, and fold it back in when the parenthesis closes. The input is always a valid expression.

Hint

Saving both the result and the sign before a parenthesis is what makes nested groups work.

Test cases

case 1
in: ["1 + 1"]
expected: 2
case 2
in: [" 2-1 + 2 "]
expected: 3
case 3
in: ["(1+(4+5+2)-3)+(6+8)"]
expected: 23
case 4
in: ["2-(5-6)"]
expected: 3
case 5
in: ["-(2+3)"]
expected: -5
Starter codePython
def basic_calculator_with_parens(s):
    # Your code here
    pass

5 test cases · run your code against them in the editor