#241

Different Ways to Add Parentheses

Medium
MathStringDynamic ProgrammingRecursionMemoizationRecursionMemoization
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n^3)
Space
O(n)
O(n)
💡

Intuition

Time O(n^3)Space O(n)

The optimal solution uses memoization to store results of previously computed expressions, avoiding redundant calculations. This reduces the time complexity significantly by ensuring each unique expression is computed only once.

⚙️

Algorithm

3 steps
  1. 1Step 1: Create a memoization dictionary to store results for expressions already computed.
  2. 2Step 2: For each operator in the expression, split it and recursively compute results for the left and right parts, checking the memoization dictionary first.
  3. 3Step 3: Combine results from the left and right parts using the operator and store the results in the memoization dictionary.
solution.py20 lines
1def diffWaysToCompute(expression, memo={}):
2    if expression in memo:
3        return memo[expression]
4    if expression.isdigit():
5        return [int(expression)]
6    results = []
7    for i, char in enumerate(expression):
8        if char in '+-*':
9            left = diffWaysToCompute(expression[:i], memo)
10            right = diffWaysToCompute(expression[i + 1:], memo)
11            for l in left:
12                for r in right:
13                    if char == '+':
14                        results.append(l + r)
15                    elif char == '-':
16                        results.append(l - r)
17                    elif char == '*':
18                        results.append(l * r)
19    memo[expression] = results
20    return results

Complexity note: The time complexity is O(n^3) due to the recursive calls and the memoization lookup. The space complexity is O(n) due to the memoization storage.

  • 1Recursive breakdown of expressions leads to overlapping subproblems.
  • 2Memoization can significantly reduce redundant calculations.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.