#2232

Minimize Result by Adding Parentheses to Expression

Medium
StringEnumerationEnumerationDynamic Programming
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(1)
💡

Intuition

Time O(n)Space O(1)

Instead of checking every possible position, we can calculate the minimum value directly by iterating through the expression and keeping track of potential splits around the '+' sign. This reduces unnecessary calculations.

⚙️

Algorithm

4 steps
  1. 1Step 1: Split the expression into num1 and num2 at the '+' sign.
  2. 2Step 2: Initialize variables to track the minimum value and the best expression.
  3. 3Step 3: Iterate through possible split points in num1 and num2, calculating the potential minimum value directly.
  4. 4Step 4: Update the minimum value and expression whenever a smaller value is found.
solution.py14 lines
1def minimizeResult(expression):
2    num1, num2 = expression.split('+')
3    min_value = float('inf')
4    result_expression = ''
5    for i in range(len(num1) + 1):
6        for j in range(len(num2)):
7            left = num1[:i] or '1'
8            right = num2[j:]
9            middle = num1[i:] + num2[:j]
10            value = int(left) * (int(middle) + int(right))
11            if value < min_value:
12                min_value = value
13                result_expression = f'{left}({middle}+{right})'
14    return result_expression

Complexity note: The time complexity is O(n) because we only iterate through the string once to find the minimum value. The space complexity is O(1) since we are using a constant amount of space.

  • 1The placement of parentheses significantly affects the result of the expression.
  • 2Understanding how multiplication distributes over addition is key to minimizing the result.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.