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
Expression Tree: "2*3-4"2*3-4Split *Split -"2""3-4""2*3""4"Split -"3""4"Results:Left branch: 2 * (3-4) = 2 * (-1) = -2Right branch: (2*3) - 4 = 6 - 4 = 2Final answer: [-2, 2]
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

n
2n
โœ“ Linear Growth
Space Complexity
O(n * 4^n)

Space for memoization cache plus recursion stack and result storage

n
2n
โšก 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
Asked in
Google 45 Amazon 38 Meta 32 Microsoft 28 Apple 22
68.3K Views
Medium Frequency
~25 min Avg. Time
2.8K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen