Different Ways to Add Parentheses - Problem
Ever wondered how mathematical expressions can be evaluated in different ways? Given a string expression containing numbers and operators (+, -, *), your task is to return all possible results from computing all the different ways to group numbers and operators using parentheses.
Think of it as exploring every possible way to parenthesize an arithmetic expression. For example, "2-1-1" can be computed as ((2-1)-1) = 0 or (2-(1-1)) = 2.
Key Points:
- You can add parentheses anywhere to change the order of operations
- Return results in any order
- All results fit in a 32-bit integer
- Number of different results โค 104
Input & Output
example_1.py โ Basic Expression
$
Input:
"2-1-1"
โบ
Output:
[0, 2]
๐ก Note:
((2-1)-1) = 0 and (2-(1-1)) = 2. Two different ways to parenthesize give different results.
example_2.py โ Mixed Operations
$
Input:
"2*3-4*5"
โบ
Output:
[-34, -14, -10, -10, 10]
๐ก Note:
Different parenthesizations: (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
example_3.py โ Single Number
$
Input:
"5"
โบ
Output:
[5]
๐ก Note:
No operators present, so only one possible result which is the number itself.
Visualization
Tap to expand
Understanding the Visualization
1
Root Expression
Start with the complete expression "2*3-4"
2
Split at Operators
Create branches for each possible operator split point
3
Recursive Calculation
Each branch recursively evaluates its left and right parts
4
Combine Results
Merge all possible combinations from left and right subtrees
Key Takeaway
๐ฏ Key Insight: Every arithmetic expression can be viewed as a binary tree where internal nodes are operators and leaves are operands. By exploring all possible tree structures, we find all possible evaluation results!
Time & Space Complexity
Time Complexity
O(n * 4^n)
Memoization reduces redundant calculations but we still explore all possible splits
โ Linear Growth
Space Complexity
O(n * 4^n)
Space for memoization cache plus recursion stack and result storage
โก Linearithmic Space
Constraints
- 1 โค expression.length โค 20
-
expression consists of digits and the operator
+,-, and* -
All the integer values in the input expression are in the range
[0, 99] - The number of different results โค 104
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code