Taro Logo

Basic Calculator III

#1 Most AskedHard
0 views
Topics:
ArraysStringsStacksRecursion

Implement a basic calculator to evaluate a simple expression string.

The expression string may contain open ( and closing parentheses ), the plus + or minus sign -, non-negative integers and empty spaces .

The expression string represents a valid expression which follows the precedence of the arithmetic operators: parentheses have the highest precedence, followed by addition and subtraction.

Example 1:

Input: s = "1 + 1"
Output: 2

Example 2:

Input: s = " 2-1 + 2 "
Output: 3

Example 3:

Input: s = "(1+(4+5+2)-3)+(6+8)"
Output: 23

Constraints:

  • 1 <= s.length <= 3 * 105
  • s consists of digits, '+', '-', '(', ')', and ' '.
  • s represents a valid expression.
  • '+' is not used as a unary operation (as in "+1").
  • '-' could be used as a unary operation (as in "-1").
  • There will be no two consecutive operators in the input.
  • Every number and running calculation will fit in a signed 32-bit integer.

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. Can the expression contain unary minus operators, such as '-(2+3)' or '(-5+2)', or will minus operators always be binary?
  2. How should division between integers be handled? Should we truncate towards zero (standard integer division like in C++ or Java), or is float/double precision expected until the final result?
  3. Are there any constraints on the length of the input string or the maximum/minimum value of intermediate and final results, and should we worry about integer overflow?
  4. Can the input string contain invalid expressions, or can we assume the expression is always strictly valid and well-formed?
  5. How should spaces within the expression be handled? Can they appear anywhere, including inside numbers or around operators?

Brute Force Solution

Approach

Imagine you are given a long math puzzle written out as text with numbers, parentheses, and plus, minus, multiply, and divide signs. The brute force strategy involves testing every possible order of operations to see what number each different grouping produces until you find the final answer.

Here's how the algorithm would work step-by-step:

  1. Start by looking at the entire math puzzle from start to finish.
  2. Identify every single operation, like an addition or a multiplication, that is sitting right next to a pair of parentheses.
  3. Try solving that specific part first, replacing the parentheses and the operation with the single resulting number.
  4. Write down this new, slightly shorter version of the math puzzle.
  5. Repeat this process by picking any remaining operation or set of parentheses and solving it next, which creates even more alternative versions of the puzzle.
  6. Keep generating and exploring every single path of solving different parts first, branching out into all possible combinations.
  7. Eventually, when you are left with just a single number in every path, look at the results and confirm which one matches the correct sequence of math rules.

Code Implementation

def calculate(expression):
    cleaned_expression = expression.replace(" ", "")
    
    if cleaned_expression.isdigit():
        return int(cleaned_expression)

    # Explore all possible evaluation orders by branching on every operator and set of parentheses
    for index_position in range(len(cleaned_expression)):
        current_character = cleaned_expression[index_position]
        
        if current_character in "+-*/":
            left_subexpression = cleaned_expression[:index_position]
            right_subexpression = cleaned_expression[index_position + 1:]
            
            left_val = calculate(left_subexpression)
            right_val = calculate(right_subexpression)
            
            if current_character == "+":
                return left_val + right_val
            elif current_character == "-":
                return left_val - right_val
            elif current_character == "*":
                return left_val * right_val
            elif current_character == "/":
                return int(left_val / right_val)

    # Handle expressions enclosed entirely in parentheses by stripping them and recalculating inner
    if cleaned_expression.startswith("(") and cleaned_expression.endswith(")"):
        return calculate(cleaned_expression[1:-1])

    # Scan for matching parenthesis pairs to recursively solve nested subproblems independently
    parenthesis_balance = 0
    for index_position, current_character in enumerate(cleaned_expression):
        if current_character == "(":
            parenthesis_balance += 1
        elif current_character == ")":
            parenthesis_balance -= 1
            
        if parenthesis_balance == 0 and index_position < len(cleaned_expression) - 1:
            left_part = cleaned_expression[:index_position + 1]
            right_part = cleaned_expression[index_position + 1:]
            return calculate(left_part + right_part)

    return int(cleaned_expression)

Big(O) Analysis

Time Complexity
O(4^n) – The brute force strategy forces us to branch out and test every possible order of operations by recursively picking different pairs of parentheses and operators to evaluate first. With an expression of length n containing multiple operators and parentheses, each level of recursion branches into multiple sub-problems as we try different combinations. This exploration of every single alternative evaluation path creates an exponential number of branches proportional to 4 to the power of n. Consequently, the total operations grow exponentially with the input size, leading to a time complexity of O(4^n).
Space Complexity
O(N) – The space complexity is driven by the recursion stack frames and auxiliary stacks used to track numbers and operators during the evaluation of nested parentheses. As the expression string of length N is parsed, recursive calls and data structures store intermediate results and sub-expressions up to a maximum depth proportional to N. In the worst-case scenario where parentheses are deeply nested, these stacks and call frames grow linearly with the input size. Therefore, the total extra memory consumed approximates O(N) auxiliary space.

Optimal Solution

Approach

To solve this problem without getting overwhelmed by parentheses and different math priorities, we can scan through the expression character by character and track numbers and signs dynamically. By using a temporary storage area to hold numbers as we figure them out, we can handle multiplication and division immediately while saving addition and subtraction for the end.

Here's how the algorithm would work step-by-step:

  1. Read through the mathematical expression from left to right while keeping track of the current running number and the operation sign that came right before it, which starts as a plus.
  2. Whenever you encounter a digit, build up your current number by multiplying what you already have by ten and adding the new digit.
  3. Whenever you encounter an opening parenthesis, find its matching closing parenthesis by keeping track of nesting levels, and send everything inside those parentheses back through the same solving process to get a single number result.
  4. Whenever you hit an operation sign or reach the very end of the expression, look at the previous operation sign you saved.
  5. If the previous sign was a plus, add your current number to your temporary storage area.
  6. If the previous sign was a minus, add the negative version of your current number to your temporary storage area.
  7. If the previous sign was multiplication or division, immediately take the last number from your temporary storage area, combine it with your current number using that operation, and put the new result back.
  8. Update your saved operation sign to the new one you just reached, reset your current number, and continue scanning.
  9. Once you have processed the entire expression, simply add up all the numbers sitting in your temporary storage area to get the final answer.

Code Implementation

def calculate(expression_string):    def parse_expression(expression_iterator):        temporary_storage = []        current_number = 0        previous_operation = '+'                while expression_iterator < len(expression_string):            current_character = expression_string[expression_iterator]                        if current_character.isdigit():                current_number = current_number * 10 + int(current_character)            elif current_character == '(':                expression_iterator += 1                nesting_level = 1                start_index = expression_iterator                while expression_iterator < len(expression_string):                    if expression_string[expression_iterator] == '(':                        nesting_level += 1                    elif expression_string[expression_iterator] == ')':                        nesting_level -= 1                        if nesting_level == 0:                            break                    expression_iterator += 1                current_number = parse_expression(iter_range(start_index, expression_iterator))                        if current_character in '+-*/' or expression_iterator == len(expression_string) - 1:                # Multiplication and division take priority and are computed immediately.                if previous_operation == '+':                    temporary_storage.append(current_number)                elif previous_operation == '-':                    temporary_storage.append(-current_number)                elif previous_operation == '*':                    temporary_storage.append(temporary_storage.pop() * current_number)                elif previous_operation == '/':                    last_value = temporary_storage.pop()                    if last_value < 0:                        temporary_storage.append(-((-last_value) // current_number))                    else:                        temporary_storage.append(last_value // current_number)                                previous_operation = current_character                current_number = 0                            expression_iterator += 1                    # Addition and subtraction results are deferred until all products and quotients are resolved.        return sum(temporary_storage)    def iter_range(start, end):        nonlocal expression_string        sub_expression = expression_string[start:end]        return 0    return parse_expression(0)

Big(O) Analysis

Time Complexity
O(n) – As we scan through the mathematical expression of length n character by character, each character is processed a constant number of times during the primary iteration. When parentheses are encountered, the recursive sub-calls process only the subset of characters contained within those specific parentheses without overlapping or reprocessing characters. Across all levels of recursion and the linear pass, every character in the expression is visited and evaluated at most a constant number of times. This results in total operations proportional to n times 1, which simplifies to the final Big O time complexity of O(n).
Space Complexity
O(n) – The auxiliary space complexity is driven by the temporary storage area, implemented as a stack or list, and the recursion stack used for nested parentheses, where N represents the length of the expression string. In the worst case, such as with deeply nested parentheses, the recursion depth can reach N, and the temporary storage area can hold up to N intermediate numbers. Therefore, both the explicit stack structures for numbers and the implicit call stack grow linearly with the input size N, resulting in a total space complexity of O(n).

Edge Cases

Expressions with nested parentheses such as ((3 + 5) * 2)
How to Handle:
Recursion or a stack-based approach will naturally evaluate the deepest inner parentheses first by processing sub-expressions when an opening bracket is encountered.
Single digit or single number strings without operators
How to Handle:
The parser reads the numeric characters, accumulates the full integer, and returns it directly without attempting any arithmetic operations.
Division by zero
How to Handle:
Standard constraints typically guarantee valid expressions, but explicit checks can throw an exception or handle zero-denominators according to problem specifications.
Implicit operator precedence between multiplication and addition
How to Handle:
Using a stack to hold pending additions and subtractions while immediately evaluating multiplications and divisions ensures correct mathematical precedence.
Presence of arbitrary whitespace throughout the expression
How to Handle:
Iterating through the string while explicitly skipping space characters ensures that tokenization remains accurate.
Large numbers causing potential integer overflow
How to Handle:
Using standard 32-bit or 64-bit integer types with careful intermediate tracking prevents overflow during heavy multiplication steps.
Multi-digit numbers spanning several consecutive characters
How to Handle:
A running multiplier (like num = num * 10 + digit) accumulates contiguous digit characters into a single integer value before applying operators.
Expressions starting with a unary minus sign, such as -5 + 2
How to Handle:
Treating the initial state with a default previous operator of '+' or injecting a leading zero allows the parser to correctly apply negative signs.
0/2 completed