Problem · String

Minimize Expression with Parentheses

Learn this problem
HardPinterest logoPinterestINTERNOA

Problem statement

You are given a string expression in the form num1+num2, where num1 and num2 are positive integers.

Insert exactly one left parenthesis somewhere to the left of the plus sign and exactly one right parenthesis somewhere to the right of the plus sign. Digits immediately outside the parentheses are multiplied by the value inside them. A missing factor on either side is treated as 1.

Return any valid parenthesized expression whose numeric value is as small as possible. If several placements produce the same minimum value, any of them is valid.

Function

minimizeExpressionWithParentheses(expression: String) → String

Examples

Example 1

expression = "247+38"return = "2(47+38)"

The placement 2(47+38) evaluates to 2 × 85 = 170, which is the minimum over all valid placements.

Example 2

expression = "12+34"return = "1(2+3)4"

The placement 1(2+3)4 evaluates to 1 × 5 × 4 = 20, the smallest possible value.

Example 3

expression = "999+999"return = "(999+999)"

Putting both full numbers inside the parentheses gives 999 + 999 = 1998. Every placement with an outside factor is larger.

Constraints

  • 3 <= expression.length <= 10
  • expression contains digits from '1' through '9' and exactly one plus sign '+'.
  • expression starts and ends with a digit.
  • Every value produced by a valid parenthesis placement fits in a signed 32-bit integer.

More Pinterest problems

drafts saved locally
public String minimizeExpressionWithParentheses(String expression) {
  // write your code here
}
expression"247+38"
expected"2(47+38)"
checking account