Taro Logo

Basic Calculator II

#10 Most AskedMedium
0 views
Topics:
StringsStacks

Given a string s which represents an expression, evaluate this expression and return its value. 

The integer division should truncate toward zero.

You may assume that the given expression is always valid. All intermediate results will be in the range of [-231, 231 - 1].

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

Example 1:

Input: s = "3+2*2"
Output: 7

Example 2:

Input: s = " 3/2 "
Output: 1

Example 3:

Input: s = " 3+5 / 2 "
Output: 5

Constraints:

  • 1 <= s.length <= 3 * 105
  • s consists of integers and operators ('+', '-', '*', '/') separated by some number of spaces.
  • s represents a valid expression.
  • All the integers in the expression are non-negative integers in the range [0, 231 - 1].
  • The answer is guaranteed to fit in a 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 parentheses, or are we guaranteed a flat expression with only basic arithmetic operators?
  2. How should we handle potential intermediate or final integer overflow/underflow, and what are the constraints on the size of the input string and the values of the operands?
  3. Are spaces allowed anywhere within the string, including leading or trailing spaces?
  4. How should invalid expressions or malformed inputs be handled, or can we assume the input string is always a valid expression?
  5. Regarding the integer division rule, should standard truncation toward zero be used for negative results as well (e.g., -3 / 2 = -1)?

Brute Force Solution

Approach

Imagine you have a math expression written out on a long paper strip with numbers and basic signs like addition, subtraction, multiplication, and division. The brute force approach involves exploring every possible way to group and calculate different parts of the expression until you are left with a single final number.

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

  1. Look at the entire expression from start to finish.
  2. Pick any two neighboring numbers and the math sign between them, and calculate their result first, pretending the rest of the expression does not exist yet.
  3. Replace those two numbers and the sign with their single calculated answer, making the expression a little bit shorter.
  4. Take this new, shorter expression and repeat the process by picking another pair of neighbors to calculate.
  5. Keep doing this over and over, trying every possible order of calculations, until you have combined everything down into one final number.
  6. Compare the final numbers you get from the different possible orders to make sure you follow the proper rules of math where multiplication and division happen before addition and subtraction.

Code Implementation

def calculate(expression_string):
    def parse_tokens(expression):
        tokens_list = []
        current_number = 0
        
        # We iterate character by character to separate multi-digit numbers from operators
        for character in expression:
            if character.isdigit():
                current_number = current_number * 10 + int(character)
            elif character in "+-*/":
                tokens_list.append(current_number)
                tokens_list.append(character)
                current_number = 0
        tokens_list.append(current_number)
        return tokens_list

    def evaluate_expression(tokens):
        if len(tokens) == 1:
            return tokens[0]

        # We explore all combinations by picking adjacent pairs to respect mathematical associativity
        for index in range(1, len(tokens), 2):
            operator = tokens[index]
            left_operand = tokens[index - 1]
            right_operand = tokens[index + 1]

            if operator == '+':
                sub_result = left_operand + right_operand
            elif operator == '-':
                sub_result = left_operand - right_operand
            elif operator == '*':
                sub_result = left_operand * right_operand
            elif operator == '/':
                sub_result = int(left_operand / right_operand)

            new_tokens = tokens[:index - 1] + [sub_result] + tokens[index + 2:]
            
            # We recursively attempt to reduce the remaining expression down to a single value
            final_result = evaluate_expression(new_tokens)
            if final_result is not None:
                return final_result

    cleaned_expression = expression_string.replace(" ", "")
    initial_tokens = parse_tokens(cleaned_expression)
    
    # We prioritize multiplication and division paths over addition and subtraction
    operator_precedence_sorted_tokens = sorted(
        [initial_tokens],
        key=lambda current_tokens: any(operator in current_tokens for operator in ['*', '/']),
        reverse=True
    )

    for candidate_tokens in operator_precedence_sorted_tokens:
        evaluated_value = evaluate_expression(candidate_tokens)
        if evaluated_value is not None:
            return evaluated_value

    return 0

Big(O) Analysis

Time Complexity
O(n^n) – To find the final result, the algorithm recursively branches out to explore every possible way to group and calculate different pairs of numbers in the expression of length n. At each step, the expression length decreases, leading to a combinatorial explosion of possible evaluation orders similar to generating permutations. This recursive exploration of all computational sequences generates an exponential number of states and paths. Consequently, the total operations approximate an exponential growth factor relative to the input size n, which simplifies to O(n^n).
Space Complexity
O(N) – To implement the step-by-step reduction of the expression where intermediate values are combined, we utilize an auxiliary stack data structure. In the worst-case scenario, such as an expression containing only addition or subtraction operations, the stack will store every number and intermediate result from the input. As the input length N increases, the maximum number of elements held in this stack grows in direct proportion to N. Therefore, the auxiliary space complexity simplifies to Big O of N.

Optimal Solution

Approach

The optimal strategy is like keeping a running tally of math chunks, using a clever trick to handle multiplication and division immediately while saving addition and subtraction for the very end. By walking through the expression from left to right and remembering the most recent operation we saw, we can process everything cleanly in a single pass without getting confused by the order of operations.

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

  1. Start looking at the math expression from the very beginning.
  2. Keep track of the numbers as you read them, building full multi-digit numbers if necessary.
  3. Also keep track of the math sign that came right before the number you are currently looking at.
  4. If the previous sign was addition, treat the current number as positive and hold onto it.
  5. If the previous sign was subtraction, treat the current number as negative and hold onto it.
  6. If the previous sign was multiplication, take the number you were holding, multiply it by the current number, and hold onto that new result instead.
  7. If the previous sign was division, take the number you were holding, divide it by the current number, and hold onto that new result instead.
  8. Whenever you finish processing a chunk, update your holding area and get ready for the next piece.
  9. At the very end of the expression, add up all the numbers and chunks you have saved up in your holding area to get your final answer.

Code Implementation

def calculate(expression_string):
    current_number = 0
    previous_operator = '+'
    number_stack = []

    for character_index, character_value in enumerate(expression_string):
        if character_value.isdigit():
            current_number = (current_number * 10) + int(character_value)

        if not character_value.isdigit() and character_value != ' ' or character_index == len(expression_string) - 1:
            # Immediate execution of multiplication and division preserves the correct operator precedence.
            if previous_operator == '+':
                number_stack.append(current_number)

            elif previous_operator == '-':
                number_stack.append(-current_number)

            elif previous_operator == '*':
                previous_value = number_stack.pop()
                number_stack.append(previous_value * current_number)

            elif previous_operator == '/':
                previous_value = number_stack.pop()
                number_stack.append(int(previous_value / current_number))

            previous_operator = character_value
            current_number = 0

    # Summing all accumulated values resolves the lower precedence addition and subtraction.
    return sum(number_stack)

Big(O) Analysis

Time Complexity
O(n) – The input size n represents the total number of characters in the math expression string. We iterate through this string exactly once from left to right, building multi-digit numbers and immediately evaluating multiplication or division chunks as we encounter them. Each character is examined and processed in constant time using a stack or running sum variable. Since the total operations scale linearly with the length of the string, the workload approximates 1 * n operations, which simplifies to O(n).
Space Complexity
O(N) – To implement the holding area mentioned in the steps, we use an auxiliary stack data structure to store intermediate results and chunks as we iterate through the expression. In the worst-case scenario, such as an expression consisting entirely of additions or subtractions, every number and its evaluated chunk will be pushed onto this stack. As the input length N grows, the maximum number of elements held in this stack scales linearly with N. Therefore, the total extra memory required is directly proportional to the size of the input string.

Edge Cases

Input string contains arbitrary spaces between numbers and operators
How to Handle:
We must skip whitespace characters during iteration so they do not disrupt number parsing.
Multi-digit numbers spanning several characters
How to Handle:
Accumulate consecutive digit characters into a running number variable before applying operators.
Precedence of multiplication and division over addition and subtraction
How to Handle:
Use a stack to defer addition and subtraction while immediately executing multiplication and division with the last stack element.
Integer division with negative results truncating toward zero
How to Handle:
Using standard integer division in languages like C++ or Java naturally truncates toward zero.
Single-element expressions containing only a non-negative integer
How to Handle:
The loop processes the single number and pushes it to the stack, which then sums up to the correct value.
Expressions starting with a unary minus or plus sign
How to Handle:
Treat the initial sign as operating against an implicit leading zero to correctly initialize the stack.
Maximum length expressions leading to intermediate value overflow
How to Handle:
Ensure intermediate calculation variables use standard 32-bit or 64-bit signed integers to prevent overflow errors.
Division by zero within the expression
How to Handle:
Assume valid problem constraints guarantee no division by zero will occur in the input.
0/17 completed