Design Gurus Logo
Basic Calculator (Hard)

Problem Statement

Given a string s, representing the arithmetic expressions, evaluate the expression and return the resultant value.

Constraints:

  • s contains digits, '+', '-', '(', ')', and ' '.
  • '+' is used as addition operation but not as a unary operator. (i.e., "+2" and "+(1 + 3)" is invalid).
  • '-' is used as a unary and subtraction operator both. (i.e., "-2" and "-(1 + 3)" is valid).

Note: You are not allowed to use the built-in function like eval() to evaluate the mathematical expression.

Examples

  • Example 1:

    • Input: "3 - (2 - 1) + 4"
    • Expected Output: 6
    • Justification: The expression inside the parentheses 2 - 1 evaluates to 1. So the expression becomes 3 - 1 + 4, which sums up to 6.
  • Example 2:

    • Input: "10 + (8 - (4 + 2)) - 1"
    • Expected Output: 11
    • Justification: Inside the inner parentheses, 4 + 2 equals 6. The expression becomes 10 + (8 - 6) - 1. Then 8 - 6 equals 2, so it simplifies to 10 + 2 - 1, which is 11.
  • Example 3:

    • Input: "5 + (3 - (2 + (8 - 5)) + 7) - (6 - 4)"
    • Expected Output: 8
    • Justification: In the innermost parentheses, 8 - 5 equals 3. The expression becomes 5 + (3 - (2 + 3) + 7) - (6 - 4). The next inner expression 2 + 3 equals 5, so it becomes 5 + (3 - 5 + 7) - 2. Simplifying further to 5 + 5 - 2, we get 10 - 2, which is 8.

Try it yourself

Try solving this question here:

Python3
Python3

. . . .

.....

.....

.....

Unlock this and all other premium problems.
No code editor for this lesson
This lesson focuses on concepts and theory