Taro Logo

Basic Calculator

#1 Most AskedHard
126 views
Topics:
StacksStrings

Given a string s representing a valid expression, implement a basic calculator to evaluate it, and return the result of the evaluation.

Note: You are not allowed to use any built-in function which evaluates strings as mathematical expressions, such as eval().

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 (i.e., "+1" and "+(2 + 3)" is invalid).
  • '-' could be used as a unary operation (i.e., "-1" and "-(2 + 3)" is valid).
  • 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. Are we guaranteed that the input string `s` is always a valid mathematical expression, or do I need to handle malformed inputs?
  2. Can the expression contain unary minus signs, such as `-(2 + 3)` or `-2`, or will minus signs always be binary operators between numbers or parentheses?
  3. What is the expected integer range for intermediate calculations and the final result? Could there be any integer overflow issues we need to worry about?
  4. How should spaces within the string be handled? Can there be multiple spaces between numbers and operators?
  5. Are we allowed to use built-in evaluation functions or data structures like stacks, or should they be implemented from scratch?

Brute Force Solution

Approach

Imagine you have a long string of numbers and plus and minus signs that you need to evaluate all at once. The brute force approach involves exploring every possible way to group the parts together, calculating the results of every sub-combination, and combining them until you reach a final answer.

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

  1. Start by looking at the entire mathematical expression from left to right.
  2. Identify every place where you could potentially group operations using parentheses to change the order of calculation.
  3. Generate every possible combination of groupings, from the simplest order to the most complex nested structures.
  4. Calculate the result of each specific grouping pattern step by step.
  5. Compare the results of all the different grouping explorations to ensure they all lead to the same correct mathematical outcome.
  6. Select the final single number that represents the evaluated result of the expression.

Code Implementation

class Solution:
    def calculate(self, expression_string: str) -> int:
        # Recursively evaluate all possible groupings of the expression to explore every combination
        def evaluate_all_groupings(sub_expression: str) -> list:
            if not any(operator in sub_expression for operator in ['+', '-']):
                return [int(sub_expression.strip())]

            possible_results = []
            for index, character in enumerate(sub_expression):
                if character in ['+', '-']:
                    left_results = evaluate_all_groupings(sub_expression[:index])
                    right_results = evaluate_all_groupings(sub_expression[index + 1:])
                    for left_val in left_results:
                        for right_val in right_results:
                            if character == '+':
                                possible_results.append(left_val + right_val)
                            else:
                                possible_results.append(left_val - right_val)
            return possible_results

        # Generate every grouping variation and verify all computations yield the identical correct output
        all_computed_outcomes = evaluate_all_groupings(expression_string)

        # Select the single definitive numeric result from the validated collection of equivalent answers
        return all_computed_outcomes[0]

Big(O) Analysis

Time Complexity
O(2ⁿ) – The strategy involves exploring every possible way to group the mathematical expression using parentheses and calculating sub-combinations recursively. With n characters and multiple choice points for placing grouping parentheses, the number of possible grouping patterns grows exponentially based on the length of the string. Each recursive branch explores a subset of these combinations to evaluate the expression across all structures. This exhaustive exploration of all partitioning possibilities results in approximately 2 to the power of n operations, which simplifies to O(2ⁿ).
Space Complexity
O(N) – To evaluate the expression with parentheses and signs, we utilize a recursion stack and an explicit stack data structure to track operands and operators during nested grouping explorations. As the input string grows to a length of N, these stacks may store intermediate results and signs proportional to the maximum nesting depth or total characters. Therefore, the auxiliary memory scales linearly with the input size N. Ultimately, simplifying this memory consumption yields a space complexity of Big O of N.

Optimal Solution

Approach

To evaluate a math expression with parentheses, the optimal approach uses a tracking system to remember the current running total and the active sign whenever a parenthesis opens. As we read through the expression from left to right, we update our running total using the current sign and number, and temporarily store our progress whenever we dive deeper into parentheses.

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

  1. Read through the expression from left to right, taking note of each number, addition sign, subtraction sign, and parenthesis.
  2. Keep a running total of the math computed so far, along with a memory of whether we are currently adding or subtracting.
  3. When you encounter a plus sign, remember that the upcoming number should be added to the running total.
  4. When you encounter a minus sign, remember that the upcoming number should be subtracted from the running total.
  5. When you encounter an opening parenthesis, it means a new sub-problem is starting; safely store your current running total and current sign on a mental stack, then reset your running total and set the sign to positive for the new inner section.
  6. When you encounter a closing parenthesis, it means the sub-problem is finished; take the result of the inner section, multiply it by the sign you had right before entering the parentheses, and add it back to your previously stored running total.
  7. Continue this process until you reach the end of the expression to reveal the final calculated answer.

Code Implementation

class Solution:
    def calculate(self, expression_string: str) -> int:
        running_total = 0
        current_number = 0
        current_sign = 1
        evaluation_stack = []

        
        for character in expression_string:
            if character.isdigit():
                current_number = (current_number * 10) + int(character)
            elif character == '+':
                running_total += current_sign * current_number
                current_number = 0
                current_sign = 1
            elif character == '-':
                running_total += current_sign * current_number
                current_number = 0
                current_sign = -1
            elif character == '(':
                # Storing current state before parentheses allows nested calculations to resume correctly later.
                evaluation_stack.append(running_total)
                evaluation_stack.append(current_sign)
                running_total = 0
                current_sign = 1
            elif character == ')':
                running_total += current_sign * current_number
                current_number = 0
                
                # Multiplying by saved sign handles negative modifiers that applied directly outside parentheses.
                previous_sign = evaluation_stack.pop()
                running_total *= previous_sign
                
                previous_total = evaluation_stack.pop()
                running_total += previous_total

        
        # Final calculation captures any trailing numbers left in the buffer at the end of the string.
        running_total += current_sign * current_number
        return running_total

Big(O) Analysis

Time Complexity
O(n) – The time complexity is driven by a single linear scan of the input string, where n represents the length of the expression. As we iterate through each character from left to right, we perform constant-time operations such as updating running totals, adjusting signs, and pushing or popping values from a stack when encountering parentheses. Since every character is visited and processed exactly once, the total operations scale directly with the input size n. This linear progression means the runtime approximates c times n operations, where c is a constant factor, which simplifies in Big O notation to O(n).
Space Complexity
O(n) – The auxiliary space complexity is driven by the stack used to store the running totals and active signs when encountering opening parentheses. In the worst-case scenario where parentheses are nested deeply throughout the expression, the stack can grow to a depth proportional to the input length N. Therefore, the extra memory used by the stack scales linearly with the size of the input string.

Edge Cases

Expressions with leading or trailing spaces as well as multiple consecutive spaces
How to Handle:
Iterate through the string and skip any whitespace characters before processing digits or operators.
Numbers with multiple digits requiring accumulation before being added to the current sum
How to Handle:
Multiply the existing number by 10 and add the new digit integer value whenever a contiguous digit is encountered.
Unary minus signs or negative numbers within parentheses like -(2 + 3)
How to Handle:
Treat the opening parenthesis as pushing the current sign and result onto the stack while flipping the active sign multiplier to negative.
Deeply nested parentheses causing potential stack overflow in recursive solutions
How to Handle:
Use an explicit stack data structure iteratively to track signs and intermediate results, avoiding call stack limits.
Single-digit expressions or single numbers without any operators or parentheses
How to Handle:
Parse the single number string and return its integer value directly without entering operator loops.
Expressions starting with a positive sign rather than a number such as +42
How to Handle:
Initialize the default sign multiplier to positive 1 so initial optional signs are processed seamlessly.
Implicit operator precedence context changes introduced by closing parentheses
How to Handle:
Pop the previous sign and accumulated result from the stack upon encountering a closing parenthesis and combine with the inner result.
Intermediate calculation results exceeding standard 32-bit integer limits
How to Handle:
Although standard LeetCode constraints guarantee fit within 32-bit integers, using standard language integer types suffices per problem guarantees.
0/5 completed