Minimize Result by Adding Parentheses to Expression - Problem

You are given a 0-indexed string expression of the form "<num1>+<num2>" where <num1> and <num2> represent positive integers.

Add a pair of parentheses to expression such that after the addition of parentheses, expression is a valid mathematical expression and evaluates to the smallest possible value. The left parenthesis must be added to the left of '+' and the right parenthesis must be added to the right of '+'.

Return expression after adding a pair of parentheses such that expression evaluates to the smallest possible value. If there are multiple answers that yield the same result, return any of them.

The input has been generated such that the original value of expression, and the value of expression after adding any pair of parentheses that meets the requirements fits within a signed 32-bit integer.

Input & Output

Example 1 — Basic Case
$ Input: expression = "247+38"
Output: "(247+38)"
💡 Note: We can place parentheses as: (247+38)=285, (247)+38=247*38=9386, 2(47+38)=2*85=170, 24(7+38)=24*45=1080. The minimum is 285.
Example 2 — Different Numbers
$ Input: expression = "12+34"
Output: "(12+34)"
💡 Note: Possible placements: (12+34)=46, (12)+34=12*34=408, 1(2+34)=1*36=36. The minimum is 36, so we return "1(2+34)".
Example 3 — Single Digits
$ Input: expression = "2+3"
Output: "(2+3)"
💡 Note: Only one valid placement: (2+3)=5. This is the minimum and only option.

Constraints

  • 1 ≤ expression.length ≤ 10
  • expression consists of digits and exactly one '+'
  • All numbers in expression are positive integers

Visualization

Tap to expand
Minimize Expression Result by Adding ParenthesesInput: "247+38" → Find minimum result with parenthesesOriginal Expression"247+38"Try All Positions(...+...)Minimum Result"(247+38)"No parenthesesTest all placementsValue: 285Evaluation Examples:(247+38) = 285 ✓(247)+38 = 93862(47+38) = 17024(7+38) = 1080Addition gives smaller result than multiplicationResult: "(247+38)" evaluates to 285 (minimum)
Understanding the Visualization
1
Input
Expression "247+38" needs parentheses added
2
Process
Try all valid parentheses positions and evaluate
3
Output
Return expression with minimum evaluation result
Key Takeaway
🎯 Key Insight: Since we add multiplication by splitting the expression, keeping the full addition usually gives the minimum result
Asked in
Google 15 Microsoft 12
25.0K Views
Medium Frequency
~15 min Avg. Time
800 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