15% off all plans & roadmaps Use code
See plansDifferent Ways to Add Parentheses
- LeetCode 241
- Medium
- Dynamic Programming (DP) Patterns
- Catalan Numbers
Updated
TL;DR: You must return every value that different groupings of the expression can produce. Treat each operator as the last one applied, solve both sides recursively, and cache the results of repeated substrings.
Problem
Given a string expression made of digits and the operators +, -, and *, group the numbers and operators with parentheses in every possible way. Evaluate each grouping and return all distinct values you can reach, in any order.
The input is built so that every result fits in a 32-bit integer, and the total number of different results stays at or below 10^4.
Example 1
Input: expression = "2-1-1" Output: [0,2] Explanation: Grouping the first subtraction gives ((2-1)-1) = 0. Grouping the second subtraction gives (2-(1-1)) = 2.
Example 2
Input: expression = "2*3-4*5" Output: [-34,-14,-10,-10,10] Explanation: Five groupings produce these values. (2*(3-(4*5))) = -34, ((2*3)-(4*5)) = -14, ((2*(3-4))*5) = -10, (2*((3-4)*5)) = -10, and (((2*3)-4)*5) = 10.
Constraints
1 <= expression.length <= 20expressioncontains only digits and the characters+,-, and*.- Every integer in the expression lies between
0and99inclusive. - No integer carries a leading
+or-sign.
Constraints that matter
- The length is at most 20, and each operator needs a digit on both sides. That allows at most 9 operators, so at most C_9 = 4862 groupings exist. Exponential work is acceptable only if you avoid solving the same substring many times.
- Every operand is one or two digits with no sign. You can parse a substring with a plain integer conversion and never handle unary minus.
- The output fits in 32 bits and holds at most 10^4 distinct values. Returning every value as a list is fine, so the output size never forces a different return type.
- There are no spaces and no parentheses in the input. Splitting at an operator index gives you both sides directly, so you need no tokenizer.
Hints
Hint 1
Every full grouping has one operator that is applied last.
Hint 2
Try every operator as the last one applied.
Solution
Intuition
Every full grouping has one operator that is applied last. That operator splits the expression into a left part and a right part. Each part is a smaller expression with the same structure, so the problem divides cleanly. This is a divide and conquer problem with a Catalan structure: m operators give C_m groupings.
Picture a filing cabinet where each folder holds the list of values for one substring. Before solving a substring, you check its folder, and if it exists you take the list out instead of redoing the work.
The left part produces a set of values and the right part produces a set of values. The chosen operator combines every left value with every right value. Nothing else touches the final result, so the two sides are independent subproblems.
The same substring appears under many different outer splits. A naive recursion solves it again each time. Divide and conquer with memoization stores each substring's values once, and every later visit becomes a lookup.
Worked example
Input: expression = "2*3-4*5" Output: [-34, -14, -10, -10, 10] Explanation: The expression has two multiplications and one subtraction, so it has five valid groupings. Each grouping picks a different operator to apply last. The five results contain -10 twice because two different groupings evaluate to the same value. The dry runs below trace this input.
The Catalan Numbers infographic is part of Pro
A one-page visual of the pattern: when it applies, the steps and the invariant to keep.
Unlock the infographicSolution pattern
Catalan Numbers
Approach 1: Brute force recursionCatalan Numbers
Try every operator as the last one applied. For each operator, solve the left substring and the right substring the same way. Then combine every pair of left and right values with that operator.
The weakness is that nothing is cached. A substring such as 4*5 gets solved every time an outer split reaches it. In 2*3-4*5, the substring 4*5 is solved at least twice, and the work grows with each repeat.
The brute force still finds every grouping, so it is correct. It repeats work that the memo removes.
Steps
- If the string has no operator, parse it as an integer and return that single value.
- Scan the string from left to right, looking at each character.
- When you find an operator at index i, solve the substring before it and the substring after it.
- Combine every left value with every right value using the operator at index i, and add each result to the list.
- After the scan, return the list of all results collected from every operator.
Dry run
Trace 2*3-4*5 with the top-level splits. Each split solves its two sides in full.
- Operator at index 1 (
*): the left side2gives [2]. The right side3-4*5gives [-17, -5], from3-(4*5)and(3-4)*5. Combining gives 2*-17 = -34 and 2*-5 = -10. - Operator at index 3 (
-): the left side2*3gives [6]. The right side4*5gives [20]. Combining gives 6-20 = -14. - Operator at index 5 (
*): the left side2*3-4gives [-2, 2]. The right side5gives [5]. Combining gives -25 = -10 and 25 = 10.
The collected list is [-34, -10, -14, -10, 10]. It holds the same five values as the expected output, in a different order.
Complexity
| Time | O(m * C_m) |
|---|---|
| Space | O(m * C_m) |
Let m be the number of operators and n the string length. Each call combines the values of its two sides, and the total number of combinations across the recursion equals the number of ways the expression can be grouped, which is C_m. The recursion is at most m levels deep, and repeated calls multiply that work by up to m. The stored lists along one path hold at most C_m values each, which gives the space bound.
PythonTested in our runner
from typing import List, Optional
class Solution:
def diffWaysToCompute(self, expression: str) -> List[int]:
results = []
for i, ch in enumerate(expression):
if ch in '+-*':
# Solve both sides, then combine every pair with this operator
left = self.diffWaysToCompute(expression[:i])
right = self.diffWaysToCompute(expression[i + 1:])
for a in left:
for b in right:
if ch == '+':
results.append(a + b)
elif ch == '-':
results.append(a - b)
else:
results.append(a * b)
# No operator found, so the string is a single number
if not results:
results.append(int(expression))
return resultsApproach 2: Memoized divide and conquerOptimal
The brute force solves the same substrings again and again. The fix is to cache each substring's list of values the first time you compute it. Later visits return the cached list.
The key is the substring itself. Two calls with the same text always produce the same values, so the text works as a safe cache key. Every substring is then solved once.
The combine step stays the same. You still pair every left value with every right value at each operator. The memo only removes the repeated solving.
Steps
- Create a cache that maps a substring to its list of values.
- If the substring is already in the cache, return the stored list right away.
- Scan the substring for operators. At each operator, solve the left side and the right side through the cache.
- Combine every left value with every right value using that operator, and add the results to a local list.
- If the local list is empty, the substring is one number, so parse it and add that value.
- Store the local list in the cache under the substring, then return it.
Dry run
The optimal approach runs on 2*3-4*5. Each row is one step of the recursion. The memo column shows which substrings are cached after that step.
| Step | Call | Action | Memo after step | Returned |
|---|---|---|---|---|
| 1 | 2*3-4*5 | Miss. Try index 1 (*). Left is 2, right is 3-4*5. | {} | pending |
| 2 | 3-4*5 | Miss. Try index 1 (-). Left is 3, right is 4*5. | {} | pending |
| 3 | 4*5 | Miss. Index 1 (*) gives 4*5 = 20. Store it. | {4*5: [20]} | [20] |
| 4 | 3-4*5 | Resume. Index 1 gives 3-20 = -17. Index 3 (*) needs left 3-4. | {4*5: [20]} | pending |
| 5 | 3-4 | Miss. Index 1 (-) gives 3-4 = -1. Store it. | {4*5: [20], 3-4: [-1]} | [-1] |
| 6 | 3-4*5 | Resume. Index 3 gives (3-4)*5 = -5. Store the full list. | adds 3-4*5: [-17, -5] | [-17, -5] |
| 7 | 2*3-4*5 | Resume. Index 1 gives 2*-17 = -34 and 2*-5 = -10. Index 3 (-) needs left 2*3. | unchanged | pending |
| 8 | 2*3 | Miss. Index 1 gives 2*3 = 6. Store it. | adds 2*3: [6] | [6] |
| 9 | 2*3-4*5 | Resume. Index 3 gives 6-20 = -14, with 4*5 as a hit. Index 5 (*) needs left 2*3-4. | unchanged | pending |
| 10 | 2*3-4 | Miss. Index 1 gives 2*(3-4) = -2, with 3-4 as a hit. Index 3 gives 6-4 = 2, with 2*3 as a hit. | adds 2*3-4: [-2, 2] | [-2, 2] |
| 11 | 2*3-4*5 | Resume. Index 5 gives -25 = -10 and 25 = 10. Collect all values. | unchanged | [-34, -14, -10, -10, 10] |
The final list holds the same five values as the expected output, in a different order.
Complexity
| Time | O(C_m + n * m^2) |
|---|---|
| Space | O(C_m + n * m^2) |
Let m be the number of operators and n the string length. A cached substring is a run of consecutive tokens, so at most about m^2 distinct substrings get solved, and each is solved once. Splitting a substring with j operators at operator i costs |left| * |right| work, and summing over all splits and substrings gives O(C_m) value work. Slicing costs O(n) per operator, which adds the n * m^2 term, and the cache stores the same value lists for the space bound.
PythonTested in our runner
from typing import List, Optional
class Solution:
def diffWaysToCompute(self, expression: str) -> List[int]:
# The memo lives in this call, so every recursive call shares it
memo = {}
def solve(expr: str) -> List[int]:
if expr in memo:
return memo[expr]
results = []
for i, ch in enumerate(expr):
if ch in '+-*':
left = solve(expr[:i])
right = solve(expr[i + 1:])
for a in left:
for b in right:
if ch == '+':
results.append(a + b)
elif ch == '-':
results.append(a - b)
else:
results.append(a * b)
if not results:
results.append(int(expr))
memo[expr] = results
return results
return solve(expression)Common mistakes
- Parsing the number before checking for operators, as in
if not resultsplaced above the loop. Every expression then returns its own integer. Fix: parse only after the scan finds no operator. - Passing
expression[i:]orexpr.substring(i)as the right side. The operator stays in the right substring, so the recursion never shrinks. Fix: the right side starts ati + 1. - Creating the memo inside the recursive method, as in a Python
memo = {}written in the method body. Each call gets a fresh empty cache, so nothing is reused. Fix: create the cache once per top-level call or keep it on the object. - Looking up the memo after the recursive calls. The work is already done by then. Fix: check the cache first and return before scanning the string.
- Reversing the operands for
-, such asb - ainstead ofa - b. The left value is always the first operand. Fix: subtract right from left at every combine. - Caching a result before the base case fills it. A pure number then gets stored as an empty list, and later callers see no values. Fix: add the parsed number first, then store the list.
Edge cases
- A single number such as
7returns [7]. The string has no operator, so the base case parses it. - The input
0returns [0]. A zero operand is valid, so do not treat it as a missing value. - The input
1+1returns [2]. A single operator has exactly one grouping. - The input
0-0-0returns [0, 0]. Two groupings produce the same value, and the output keeps both copies. - The input
1+1+1+1has repeated substrings at many levels. The memo solves each substring once, and the output still contains every grouping value. - The longest inputs, at 20 characters, can produce large products. Check that every intermediate value stays within the 32-bit guarantee.
Follow-ups interviewers ask
Follow-ups are part of Pro
The questions interviewers ask after you solve Different Ways to Add Parentheses, with how to answer them.
Unlock the follow-upsDifferent Ways to Add Parentheses FAQ
What is the time complexity of Different Ways to Add Parentheses?
The memoized solution runs in O(C_m + n * m^2) time, where m is the number of operators and n is the string length. The C_m term comes from the value combinations, and the other term comes from string slicing. The brute force is O(m * C_m) because it repeats solved substrings.
Why use divide and conquer with memoization for Different Ways to Add Parentheses?
Each operator splits the expression into two independent smaller expressions. Memoization stores the values of each substring, so repeated substrings cost one lookup after the first solve. This turns a repeated recursion into one computation per distinct substring.
Can Different Ways to Add Parentheses be solved in O(1) extra space?
No, because the answer itself can hold C_m values, and the cache stores lists for every substring. Those lists need space in proportion to the output and the substrings. Only the recursion itself uses O(m) stack space beyond that.
Why does my Python memo not speed up the recursion?
The memo dictionary is probably created inside the recursive method, so each call starts with an empty cache. Create the dictionary once per top-level call, then pass it down through a nested function. The nested function shares the dictionary with every recursive call.
Is leetcode 241 a Catalan number problem?
Yes, the number of groupings for m operators is the m-th Catalan number. The same split structure appears in counting binary trees and in matrix chain grouping. The code does not compute the Catalan number, but the count explains why the work grows the way it does.
Asked at
See which companies ask this — Pro
Related problems
- Unique Binary Search Trees II · same technique: Catalan Numbers
- Unique Binary Search Trees · same technique: Catalan Numbers
- Distinct Subsequences · next harder, same pattern
- Coin Change · same pattern: Dynamic Programming (DP) Patterns
- Maximum Subarray · same pattern: Dynamic Programming (DP) Patterns
- Word Break · same pattern: Dynamic Programming (DP) Patterns
- Longest Increasing Subsequence · same pattern: Dynamic Programming (DP) Patterns
- Edit Distance · same pattern: Dynamic Programming (DP) Patterns
- House Robber · same pattern: Dynamic Programming (DP) Patterns
- Longest Common Subsequence · same pattern: Dynamic Programming (DP) Patterns