Different Ways to Add Parentheses solution explained
Different Ways to Add Parentheses is solved by choosing which operator is applied last. Split the expression at that operator, recursively collect every value the left part can take and every value the right part can take, and combine each pair with the operator. Caching results per range of tokens avoids recomputing the same sub-expression, and the output, one value per grouping, grows with the Catalan numbers.
By Evin JohnPublished 8 min read
The task in our own words
You get a string such as "4*5-2*3" made of whole numbers and the operators +, - and *. Insert parentheses in every possible way so that each operator applies to exactly two operands, evaluate each version, and return all the results in any order. Two different groupings that happen to give the same number both count, so the result list can contain duplicates.
| Expression | Results | Groupings |
|---|---|---|
| 3-1*2 | [1, 4] | 3-(1*2) = 1, (3-1)*2 = 4 |
| 10-4-3 | [9, 3] | 10-(4-3) = 9, (10-4)-3 = 3 |
| 4*5-2*3 | [-4, 36, 14, 36, 54] | Five groupings; 36 comes from both 4*((5-2)*3) and (4*(5-2))*3 |
| 7 | [7] | No operator, one value |
Questions to settle first: can numbers have several digits (yes, so parse them properly), can there be spaces or a leading minus sign (usually no), and does the order of results matter (usually not, but duplicates must stay). With three operators there are five groupings, with four there are fourteen; those are Catalan numbers again, the same sequence that counts binary search tree shapes.
Slow approach: write out every grouping
The most literal approach builds the parenthesized strings themselves. For each operator, take every fully parenthesized form of the text on its left and on its right and glue them together inside a new pair of brackets. Then evaluate every string. It reaches the right answer, but it slices strings at every level, rebuilds the same sub-expressions again and again, and leans on an evaluator, which most interviewers will ask you to remove.
def all_groupings_slow(expr):
def forms(text): # every fully parenthesized version of text
found = []
for i, ch in enumerate(text):
if ch in "+-*":
for left in forms(text[:i]):
for right in forms(text[i + 1:]):
found.append("(" + left + ch + right + ")")
return found or [text]
return [eval(f) for f in forms(expr)]Main approach: split on the last operator, with memoization
Every full parenthesization has one operator that is applied last, at the top of its expression tree. If that operator is the kth one, the left operand is some grouping of everything before it and the right operand is some grouping of everything after it, and those two choices are independent. So the set of results for the whole expression is: for each operator k, for each value a of the left side and each value b of the right side, a op b.
Parse the string once into a list of numbers and a list of operators, so that ops[k] sits between nums[k] and nums[k + 1]. Then solve(i, j) returns all values of the sub-expression from nums[i] to nums[j]. A single number is its own answer. The pair (i, j) has only O(m²) possibilities for m numbers, so a cache keyed by it stops the same range from being solved twice.
def all_groupings(expr):
nums, ops = [], []
value = 0
for ch in expr:
if ch.isdigit():
value = value * 10 + int(ch)
else:
nums.append(value)
ops.append(ch)
value = 0
nums.append(value)
memo = {}
def solve(i, j): # every value of nums[i..j] combined by ops[i..j-1]
if i == j:
return [nums[i]]
if (i, j) in memo:
return memo[(i, j)]
out = []
for k in range(i, j): # ops[k] is applied last
for a in solve(i, k):
for b in solve(k + 1, j):
if ops[k] == "+":
out.append(a + b)
elif ops[k] == "-":
out.append(a - b)
else:
out.append(a * b)
memo[(i, j)] = out
return out
return list(solve(0, len(nums) - 1))function allGroupings(expr) {
const nums = [];
const ops = [];
let value = 0;
for (const ch of expr) {
if (ch >= "0" && ch <= "9") {
value = value * 10 + Number(ch);
} else {
nums.push(value);
ops.push(ch);
value = 0;
}
}
nums.push(value);
const m = nums.length;
const memo = Array.from({ length: m }, () => new Array(m).fill(null));
function solve(i, j) {
if (i === j) return [nums[i]];
if (memo[i][j]) return memo[i][j];
const out = [];
for (let k = i; k < j; k++) {
for (const a of solve(i, k)) {
for (const b of solve(k + 1, j)) {
if (ops[k] === "+") out.push(a + b);
else if (ops[k] === "-") out.push(a - b);
else out.push(a * b);
}
}
}
memo[i][j] = out;
return out;
}
return [...solve(0, m - 1)];
}Trace "3-1*2": nums = [3, 1, 2], ops = [-, *]. With the minus applied last, the left is [3] and the right, solve(1, 2), is [2], giving 1. With the times applied last, solve(0, 1) is [2] and the right is [2], giving 4. Result [1, 4]. Both functions return a copy of the top-level list so the caller cannot mutate the cache.
Complexity
Let m be the number of operands. The answer for the whole expression has Catalan(m − 1) entries, and the cached sub-answers are smaller Catalan numbers, so the time is dominated by producing those lists: exponential in m, roughly 4^m divided by a polynomial. Without the cache, the same ranges are recomputed from scratch under many different parents, which multiplies that work further. Interview inputs are short, typically a handful of operators, so the point to make is that the work is tied to the output size, not that it is polynomial.
| Approach | Time | Extra space |
|---|---|---|
| Build strings, then evaluate | Exponential, plus string slicing and parsing at every level | All strings held at once |
| Divide and conquer, no cache | Exponential, with repeated ranges | O(m) stack plus the output |
| Divide and conquer with cache | Bounded by the total size of the O(m²) cached lists | Those cached lists |
Edge cases
- A single number with no operator, like "7": return [7].
- Multi-digit numbers such as "12+0*3": parse digits into one value instead of treating each character as its own number.
- Zeros, as in "0*5-0", need no special case, and subtraction can produce negative intermediate values, which are allowed.
- Duplicates: "4*5-2*3" yields 36 twice. Do not put the results in a set.
- Long chains of the same operator, like "1+1+1+1+1", where every grouping gives the same value. The list still has one entry per grouping.
Common mistakes
- Deduplicating results with a set because the duplicates look like a bug. The problem counts groupings, not distinct values.
- Treating each character as a number and breaking on "12".
- Using eval on sub-strings in the final answer. It works, but it is slow and many interviewers consider it a shortcut.
- Recursing on raw string slices without a cache, which costs both repeated work and repeated copying.
- Returning the cached list itself and letting the caller modify it, which corrupts later lookups.
Walking the interviewer through it
Fictional example
- Candidate
- Every grouping has one operator that runs last. If I fix that operator, the left and right sides can each be grouped any way, independently, so I combine every left value with every right value.
- Candidate
- I'll parse the string into numbers and operators first, then write solve of i and j over number indexes, with a dictionary cache so each range is computed once.
- Candidate
- The output has a Catalan number of entries, so the runtime is exponential in the number of operators no matter what. The cache just makes sure we don't do worse than that.
Related problems
This is the expression-tree twin of Unique Binary Search Trees II: there the split point is a root key, here it is an operator, and both combine every left result with every right result. If instead of listing all groupings you only need the cheapest one, the problem becomes Matrix Chain Multiplication, which uses the same ranges but keeps a single minimum per range. The algorithm interview questions page has more on divide and conquer.
Where Natively helps in practice
Recursion questions go better when you can explain the split before you code it. During practice, Natively can read the problem from a screenshot and suggest an approach you can test your own idea against, and it can transcribe a mock interview on your computer so you can review whether you justified keeping duplicates. More on that in an AI interview assistant.
Questions people ask
How do you solve Different Ways to Add Parentheses?
Pick each operator in turn as the one applied last. Recursively compute every value of the part to its left and to its right, then combine each pair with that operator. Memoize results per range of numbers so each sub-expression is solved once.
Should duplicate results be removed?
No. Each grouping contributes one result, so two groupings with the same value both appear. Putting results in a set is a common mistake.
What is the time complexity?
The number of results is the Catalan number of the operator count, which grows exponentially. Any correct solution must produce that many values, so the work is exponential in the number of operators; memoization avoids repeating it.
Is using eval acceptable in an interview?
It can produce correct answers, but it is slow and usually seen as a shortcut. Tokenize the string once and apply the operators yourself.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
