Different Ways to Add Parentheses - Problem

Given a string expression of numbers and operators, return all possible results from computing all the different possible ways to group numbers and operators. You may return the answer in any order.

The test cases are generated such that the output values fit in a 32-bit integer and the number of different results does not exceed 104.

Input & Output

Example 1 — Basic Case
$ Input: expression = "2-1-1"
Output: [0,2]
💡 Note: Two ways to parenthesize: ((2-1)-1) = 0 and (2-(1-1)) = 2
Example 2 — Multiple Operators
$ Input: expression = "2*3-4*5"
Output: [-34,-14,-10,-10,10]
💡 Note: Five ways to parenthesize giving different results based on operator precedence changes
Example 3 — Single Number
$ Input: expression = "2"
Output: [2]
💡 Note: Only one way to evaluate a single number

Constraints

  • 1 ≤ expression.length ≤ 20
  • expression consists of digits and the operators '+', '-', and '*'
  • All the integer values in the input expression are in the range [0, 99]

Visualization

Tap to expand
Different Ways to Add Parentheses INPUT Expression String: 2 - 1 - 1 Possible Groupings: (2-1) - 1 First subtract, then subtract 2 - (1-1) Second subtract first Input Values: expression = "2-1-1" 2 operators = 2 ways to split ALGORITHM STEPS 1 Divide at Operators Split at each operator 2 Recursive Solve Solve left and right parts 3 Combine Results Apply operator to all pairs 4 Base Case Single number returns itself Recursion Tree: 2-1-1 (2-1)-1 2-(1-1) 0 2 FINAL RESULT Calculation Breakdown: (2 - 1) - 1 = 1 - 1 = 0 2 - (1 - 1) = 2 - 0 = 2 Output Array: 0 2 OK - 2 unique results found Key Insight: This is a classic Divide and Conquer problem. Each operator becomes a potential split point. Recursively compute all results for left and right subexpressions, then combine using the operator. Time Complexity: O(n * 2^n) where n is number of operators. Memoization can optimize repeated subproblems. TutorialsPoint - Different Ways to Add Parentheses | Divide and Conquer Approach
Asked in
Google 42 Amazon 35 Facebook 28 Microsoft 22
185.0K Views
Medium Frequency
~25 min Avg. Time
3.4K 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