Different Ways to Add Parentheses (LeetCode 241): Solution and Explanation

Medium
Math
String
Dynamic Programming
Recursion
Memoization

Given an expression of non-negative integers joined by +, - and *, return the value of every possible full parenthesization, in any order. Different groupings that give the same number each count, so duplicates are expected.

Intuition

Writing out parenthesizations directly gets messy fast. A cleaner view: in any fully parenthesized expression, exactly one operator is evaluated last, and it sits at the top of the expression tree.

If that last operator is op at some position, everything to its left was grouped somehow into one value a, and everything to its right into one value b. The result is a op b.

So the set of values for an expression is: for every operator, every value of the left part combined with every value of the right part. The left and right parts are smaller versions of the same problem.

The same sub-expression shows up under many different splits. In 2*3-4*5, the part 4*5 is needed both when - is last and when the first * is last. Caching each sub-expression's list of values avoids recomputing it.

Approach: Divide and conquer with memoization

  1. Define ways(s) returning the list of all values of sub-expression s, with a memo keyed by s.
  2. If s is cached, return the cached list.
  3. For every operator position i in s, compute left = ways(s[:i]) and right = ways(s[i+1:]), then append a op b for every a in left and b in right.
  4. If no operator was found, s is a plain number: the list is just [int(s)].
  5. Store the list in the memo and return it. The answer is ways(expression).

Step-by-step example

expression = "2-1-1"
  1. ways("2-1-1") tries the first - as the last operator: left "2" gives [2], right "1-1" gives [0] (its only split is 1 - 1). That adds 2 - 0 = 2.
  2. Then it tries the second - as the last operator: left "2-1" gives [1], right "1" is already in the memo as [1]. That adds 1 - 1 = 0.
  3. No more operators, so ways("2-1-1") = [2, 0].
  4. These are the two groupings 2-(1-1) and (2-1)-1.

Code: Python, Java, C++

1class Solution:
2    def diffWaysToCompute(self, expression: str) -> List[int]:
3        memo = {}
4
5        def ways(s: str) -> List[int]:
6            if s in memo:
7                return memo[s]
8            res = []
9            for i, ch in enumerate(s):
10                if ch in '+-*':
11                    left = ways(s[:i])
12                    right = ways(s[i + 1:])
13                    for a in left:
14                        for b in right:
15                            res.append(a + b if ch == '+' else a - b if ch == '-' else a * b)
16            if not res:
17                res.append(int(s))
18            memo[s] = res
19            return res
20
21        return ways(expression)
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

Proportional to the output size, roughly O(n * C(k))

With k operators there are C(k) (the k-th Catalan number) full parenthesizations, and each value is produced by one combine step. With memoization each sub-expression's list is built once.

Space

O(n^2 * C(k)) in the worst case

The memo holds a list for each of the O(k^2) sub-expressions, and the largest lists have Catalan size.

Other approaches

Plain recursion without a memo (time Exponential, larger than the output, space O(n) recursion depth plus the output)

The same split-and-combine recursion, recomputing every sub-expression each time it appears. It still passes the small limits (at most 10 numbers) but does repeated work.

Bottom-up interval DP (time Same as the memoized version, space O(k^2 * C(k)))

Tokenize into numbers and operators, then fill dp[i][j] = list of values for numbers i through j, by increasing interval length, combining dp[i][k] and dp[k+1][j] across operator k. Same work, no recursion.

Common mistakes

  • Removing duplicates. Two groupings with the same value are two separate answers: 2*3-4*5 has -10 twice.
  • Parsing multi-digit numbers one character at a time. In the base case, convert the whole substring, so "11" becomes 11, not 1 and 1.
  • Treating - as part of a negative number. The input numbers never carry a sign, so every - is a binary operator.
  • Combining in only one direction. You need every pair (a, b), not just matching indices of the two lists.

Frequently asked questions

Why does picking the last operator cover every parenthesization exactly once?

A full parenthesization is a binary expression tree, and its root is the operator applied last. Different roots give different trees, and for a fixed root the trees are exactly the pairs of a left tree and a right tree, which is what the recursion enumerates.

Does the memo key need to be the substring?

No. Keying by the start and end positions works the same way and avoids building substrings. The substring key has a small bonus: identical text at different positions, like the two 1s in 2-1-1, shares one entry.

How many results can there be?

With k operators there are C(k) groupings, the Catalan number: 1, 2, 5, 14, 42, 132, 429, 1430, 4862 for k = 1 to 9. A 20-character expression has at most 9 operators, so at most 4862 values.