Off-by-one on range boundaries
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Move from brute-force thinking to an efficient approach using core interview patterns strategy.
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: Theexpressionevaluates 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 <= 10expression consists of digits from '1' to '9' and '+'.expression starts and ends with digits.expression contains exactly one '+'.expression, and the value of expression after adding any pair of parentheses that meets the requirements fits within a signed 32-bit integer.Problem summary: 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.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: General problem-solving
"247+38"
"12+34"
"999+999"
basic-calculator)different-ways-to-add-parentheses)solve-the-equation)Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #2232: Minimize Result by Adding Parentheses to Expression
class Solution {
public String minimizeResult(String expression) {
int idx = expression.indexOf('+');
String l = expression.substring(0, idx);
String r = expression.substring(idx + 1);
int m = l.length(), n = r.length();
int mi = Integer.MAX_VALUE;
String ans = "";
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
int c = Integer.parseInt(l.substring(i)) + Integer.parseInt(r.substring(0, j + 1));
int a = i == 0 ? 1 : Integer.parseInt(l.substring(0, i));
int b = j == n - 1 ? 1 : Integer.parseInt(r.substring(j + 1));
int t = a * b * c;
if (t < mi) {
mi = t;
ans = String.format("%s(%s+%s)%s", l.substring(0, i), l.substring(i),
r.substring(0, j + 1), r.substring(j + 1));
}
}
}
return ans;
}
}
// Accepted solution for LeetCode #2232: Minimize Result by Adding Parentheses to Expression
// Auto-generated Go example from java.
func exampleSolution() {
}
// Reference (java):
// // Accepted solution for LeetCode #2232: Minimize Result by Adding Parentheses to Expression
// class Solution {
// public String minimizeResult(String expression) {
// int idx = expression.indexOf('+');
// String l = expression.substring(0, idx);
// String r = expression.substring(idx + 1);
// int m = l.length(), n = r.length();
// int mi = Integer.MAX_VALUE;
// String ans = "";
// for (int i = 0; i < m; ++i) {
// for (int j = 0; j < n; ++j) {
// int c = Integer.parseInt(l.substring(i)) + Integer.parseInt(r.substring(0, j + 1));
// int a = i == 0 ? 1 : Integer.parseInt(l.substring(0, i));
// int b = j == n - 1 ? 1 : Integer.parseInt(r.substring(j + 1));
// int t = a * b * c;
// if (t < mi) {
// mi = t;
// ans = String.format("%s(%s+%s)%s", l.substring(0, i), l.substring(i),
// r.substring(0, j + 1), r.substring(j + 1));
// }
// }
// }
// return ans;
// }
// }
# Accepted solution for LeetCode #2232: Minimize Result by Adding Parentheses to Expression
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
// Accepted solution for LeetCode #2232: Minimize Result by Adding Parentheses to Expression
/**
* [2232] Minimize Result by Adding Parentheses to Expression
*
* 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 <= 10
* expression consists of digits from '1' to '9' and '+'.
* expression starts and ends with digits.
* expression contains exactly one '+'.
* 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.
*
*/
pub struct Solution {}
// problem: https://leetcode.com/problems/minimize-result-by-adding-parentheses-to-expression/
// discuss: https://leetcode.com/problems/minimize-result-by-adding-parentheses-to-expression/discuss/?currentPage=1&orderBy=most_votes&query=
// submission codes start here
impl Solution {
pub fn minimize_result(expression: String) -> String {
String::new()
}
}
// submission codes end
#[cfg(test)]
mod tests {
use super::*;
#[test]
#[ignore]
fn test_2232_example_1() {
let expression = "247+38".to_string();
let result = "2(47+38)".to_string();
assert_eq!(Solution::minimize_result(expression), result);
}
#[test]
#[ignore]
fn test_2232_example_2() {
let expression = "12+34".to_string();
let result = "1(2+3)4".to_string();
assert_eq!(Solution::minimize_result(expression), result);
}
#[test]
#[ignore]
fn test_2232_example_3() {
let expression = "999+999".to_string();
let result = "(999+999)".to_string();
assert_eq!(Solution::minimize_result(expression), result);
}
}
// Accepted solution for LeetCode #2232: Minimize Result by Adding Parentheses to Expression
function minimizeResult(expression: string): string {
const [n1, n2] = expression.split('+');
let minSum = Number.MAX_SAFE_INTEGER;
let ans = '';
let arr1 = [],
arr2 = n1.split(''),
arr3 = n2.split(''),
arr4 = [];
while (arr2.length) {
((arr3 = n2.split('')), (arr4 = []));
while (arr3.length) {
let cur = (getNum(arr2) + getNum(arr3)) * getNum(arr1) * getNum(arr4);
if (cur < minSum) {
minSum = cur;
ans = `${arr1.join('')}(${arr2.join('')}+${arr3.join('')})${arr4.join('')}`;
}
arr4.unshift(arr3.pop());
}
arr1.push(arr2.shift());
}
return ans;
}
function getNum(arr: Array<string>): number {
return arr.length ? Number(arr.join('')) : 1;
}
Use this to step through a reusable interview workflow for this problem.
Two nested loops check every pair or subarray. The outer loop fixes a starting point, the inner loop extends or searches. For n elements this gives up to n²/2 operations. No extra space, but the quadratic time is prohibitive for large inputs.
Most array problems have an O(n²) brute force (nested loops) and an O(n) optimal (single pass with clever state tracking). The key is identifying what information to maintain as you scan: a running max, a prefix sum, a hash map of seen values, or two pointers.
Review these before coding to avoid predictable interview regressions.
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.