Find Lexicographically Smallest Expression to Match Target
Dynamic ProgrammingAuto-graded · 28 test casesLast updated
Tests interval dynamic programming to build fully parenthesized expressions using all numbers in order with +, -, * operators to reach a target value.
You are given a list of non-negative integers numbers and an integer target_value. Your task is to construct a mathematical expression that uses every integer from numbers exactly once, in their original order, and evaluates to target_value.
Between each pair of consecutive numbers, you must place exactly one operator from the set {+, -, *}. Every operation must be fully parenthesized, meaning each operator application is wrapped in parentheses. For example, with three numbers, valid expressions include ((a+b)*c) and (a+(b*c)).
Return the lexicographically smallest valid expression that evaluates to target_value. If no such expression exists, return an empty string.
Note: Lexicographic comparison follows standard ASCII ordering where ( < ) < * < + < - < digits.
Constraints
2 <= len(numbers) <= 80 <= numbers[i] <= 100target_valueis an integer (may be negative)- Each expression must use all numbers in their original order
- Intermediate results may be negative or exceed the input range
Examples
Example 1
Input: find_smallest_expression([1, 2, 3], 9)
Output: '((1+2)*3)'
Example 2
Input: find_smallest_expression([2, 2], 4)
Output: '(2*2)'
Example 3
Input: find_smallest_expression([1, 2, 3], 100)
Output: ''
Example 4
Input: find_smallest_expression([7], 7)
Output: '7'
Hints
Hint 1
Think about how to break down the problem: any parenthesized expression has a root operator that splits the numbers into left and right subexpressions
Hint 2
For each subrange of numbers, track all possible values you can create and the smallest expression string for each value
Hint 3
Use interval dynamic programming: process shorter ranges first, then combine them to build longer ranges
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This problem requires building fully parenthesized expressions from a sequence of numbers. The key insight is that any such expression corresponds to a binary tree where each internal node represents an operator and each leaf is a number from the input.
We use interval dynamic programming. For each contiguous subrange of numbers, we track every possible value we can produce and store the lexicographically smallest expression that produces each value.
Algorithm:
-
Base case: For a single number at index
i, the only value isnumbers[i]and the expression is its string representation (no parentheses around single numbers). -
Building up: For a range
[start, end], we try every split pointkin between. This split represents the root operator that combines:- A left subexpression over
numbers[start..k] - A right subexpression over
numbers[k+1..end]
- A left subexpression over
-
Combining: For each possible left value
Land right valueR, we form three new expressions using+,-, and*. Each produces a result value and an expression string(left_str op right_str). -
Deduplication: Multiple expressions may produce the same value. We keep only the lexicographically smallest expression for each value. This is safe because if two expressions evaluate to the same number, choosing the smaller string now will always lead to a smaller or equal final result when combined with other subexpressions.
-
Answer: After processing all intervals, the answer is the expression for
target_valuein the range covering all numbers, or an empty string if unreachable.
Why lexicographic minimality composes: When building (L op R), if L1 and L2 both evaluate to the same value but L1 < L2 lexicographically, then (L1 op R) will always be smaller than (L2 op R) for any fixed R and operator, because both strings start with ( and the difference appears before the common suffix.
Complexity
-
Time: O(n³ · V² · n) where V is the number of distinct values per interval. The n³ comes from iterating over intervals and split points, V² from combining left and right values, and the final n from string operations. With n ≤ 8, this is acceptable.
-
Space: O(n² · V · n) for storing the DP table with expression strings.
In practice, many expressions collapse to the same value (especially with multiplication by zero or repeated operations), so the effective V is much smaller than the theoretical maximum.
from typing import List
def find_smallest_expression(numbers: List[int], target_value: int) -> str:
n = len(numbers)
if n == 0:
return ""
if n == 1:
return str(numbers[0]) if numbers[0] == target_value else ""
# dp[i][j]: dictionary mapping each reachable value to the smallest expression
# for the subrange numbers[i..j]
dp = [[{} for _ in range(n)] for _ in range(n)]
# Base case: single numbers
for i in range(n):
dp[i][i][numbers[i]] = str(numbers[i])
# Build up by increasing interval length
for length in range(2, n + 1):
for start in range(n - length + 1):
end = start + length - 1
value_to_expr = {}
# Try all possible split points
for split in range(start, end):
left_dict = dp[start][split]
right_dict = dp[split + 1][end]
# Combine each left value with each right value
for left_val, left_str in left_dict.items():
for right_val, right_str in right_dict.items():
# Try all three operators
operations = [
(left_val + right_val, "+"),
(left_val - right_val, "-"),
(left_val * right_val, "*")
]
for result_val, op in operations:
new_expr = "(" + left_str + op + right_str + ")"
existing = value_to_expr.get(result_val)
if existing is None or new_expr < existing:
value_to_expr[result_val] = new_expr
dp[start][end] = value_to_expr
return dp[0][n - 1].get(target_value, "")