Minimize Result by Adding Parentheses to Expression Problem
Description
LeetCode Problem 2232.
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.
Example 1:
Input: expression = "247+38"
Output: "2(47+38)"
Explanation: The expression evaluates to 2 * (47 + 38) = 2 * 85 = 170.
Note that "2(4)7+38" is invalid because the right parenthesis must be to the right of the '+'.
It can be shown that 170 is the smallest possible value.
Example 2:
Input: expression = "12+34"
Output: "1(2+3)4"
Explanation: The expression evaluates to 1 * (2 + 3) * 4 = 1 * 5 * 4 = 20.
Example 3:
Input: expression = "999+999"
Output: "(999+999)"
Explanation: The expression evaluates to 999 + 999 = 1998.
Constraints:
3 <= expression.length <= 10expressionconsists of digits from'1'to'9'and'+'.expressionstarts and ends with digits.expressioncontains exactly one'+'.- The original value of
expression, and the value ofexpressionafter adding any pair of parentheses that meets the requirements fits within a signed 32-bit integer.
Solution
Approach: Enumeration
The expression has the form l+r. The left parenthesis must go somewhere inside l (before any of its digits) and the right parenthesis somewhere inside r (after any of its digits), so there are at most 9 * 9 options.
For each choice, l splits into a prefix a and a suffix c1, and r splits into a prefix c2 and a suffix b. The value is a * (c1 + c2) * b, where an empty a or b counts as 1. Try every split and keep the one with the smallest value.
Complexity: O(n2) splits, each evaluated in O(n), with n the length of the expression (at most 10), so effectively constant.
from math import inf
class Solution:
def minimizeResult(self, expression: str) -> str:
l, r = expression.split("+")
m, n = len(l), len(r)
mi = inf
ans = None
for i in range(m):
for j in range(n):
c = int(l[i:]) + int(r[: j + 1])
a = 1 if i == 0 else int(l[:i])
b = 1 if j == n - 1 else int(r[j + 1 :])
if (t := a * b * c) < mi:
mi = t
ans = f"{l[:i]}({l[i:]}+{r[: j + 1]}){r[j + 1:]}"
return ans