algoadvance

Given a string expression of numbers and operators, return all possible results from computing all the different possible ways to group numbers and operators. The valid operators are +, -, and *.

Example 1:

Input: "2-1-1"
Output: [0, 2]
Explanation: ((2-1)-1) = 0 
             (2-(1-1)) = 2

Example 2:

Input: "2*3-4*5"
Output: [-34, -14, -10, -10, 10]
Explanation: 
(2*(3-(4*5))) = -34 
((2*3)-(4*5)) = -14 
((2*(3-4))*5) = -10 
(2*((3-4)*5)) = -10 
(((2*3)-4)*5) = 10

Clarifying Questions

  1. What is the length range of the input string?
    • Typically, we’ll assume it to be at most 20 characters for this problem.
  2. Are there any parentheses in the input string?
    • No, the input string will only contain digits (0-9) and operators (+, -, *).
  3. Are inputs guaranteed to be valid (e.g., no division by zero, no invalid characters)?
    • Yes, inputs are guaranteed to be valid.

Strategy

  1. Divide and Conquer:
    • We’ll use a recursive approach which divides the problem at each operator.
    • For each operator in the input string, split the expression into left and right sub-expressions.
    • Recursively evaluate each sub-expression.
  2. Combine Results:
    • For every result from the left sub-expression and every result from the right sub-expression, combine them using the current operator.
    • Store and return the combined results.
  3. Base Case:
    • When the input string is a single number, return it as the base case.

Code

def diffWaysToCompute(expression):
    def compute(left, right, op):
        results = []
        for l in left:
            for r in right:
                if op == '+':
                    results.append(l + r)
                elif op == '-':
                    results.append(l - r)
                elif op == '*':
                    results.append(l * r)
        return results

    if expression.isdigit():
        return [int(expression)]

    results = []
    for i, ch in enumerate(expression):
        if ch in "+-*":
            left = diffWaysToCompute(expression[:i])
            right = diffWaysToCompute(expression[i+1:])
            results.extend(compute(left, right, ch))
    return results

# Example usages
print(diffWaysToCompute("2-1-1"))  # Output: [0, 2]
print(diffWaysToCompute("2*3-4*5"))  # Output: [-34, -14, -10, -10, 10]

Time Complexity

Thus, while the exact number of operations is hard to pinpoint, it grows exponentially with the length of the input expression due to the nature of recursive splitting.

Try our interview co-pilot at AlgoAdvance.com