Skip to main content
Back to problems
#2232
Medium Algorithms

Minimize result by adding parentheses to expression

String Enumeration
68.2% acceptance
Feb 25, 2026
226
344
You are given a 0-indexed string expression of the form "+" where and 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.

Solution

Rust
Time O(n²)
Space O(1)
LeetCode
solution.rs
impl Solution {
  pub fn minimize_result(expression: String) -> String {
    let p = expression.find('+').unwrap();
    let _bytes = expression.as_bytes();
    let n = expression.len();
    let mut best_val = i64::MAX;
    let mut best = expression.clone();
    for l in 0..p {
      for r in p + 1..n {
        let left: i64 = if l == 0 { 1 } else { expression[0..l].parse().unwrap() };
        let inner_l: i64 = expression[l..p].parse().unwrap();
        let inner_r: i64 = expression[p + 1..r + 1].parse().unwrap();
        let right: i64 = if r == n - 1 { 1 } else { expression[r + 1..].parse().unwrap() };
        let val = left * (inner_l + inner_r) * right;
        if val < best_val {
          best_val = val;
          best = format!("{}({}+{}){}", &expression[0..l], &expression[l..p], &expression[p+1..r+1], &expression[r+1..]);
        }
      }
    }
    best
  }
}