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: "2-1-1"2-1-1↓ Try all parentheses placements ↓((2-1)-1)(2-(1-1))(1-1) = 0(1-1) = 0(2-0) = 202Final Result: [0, 2]
Understanding the Visualization
1
Input
Expression "2-1-1" with operators
2
Process
Try all possible parentheses placements
3
Output
All possible evaluation results
Key Takeaway
🎯 Key Insight: Each operator can be the last operation - use divide-and-conquer to explore all possibilities
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