Smallest Fully Bracketed Arithmetic Expression Hitting a Target
Dynamic ProgrammingAuto-graded · 31 test casesLast updated
Enumerate all operator and bracket choices over an ordered list of numbers and return the ASCII-smallest canonical expression that evaluates to the target, or an empty string.
You are given a list of non-negative integers values and an integer goal. The numbers must stay in the order given. Between each pair of neighbouring numbers you must place exactly one of the operators +, - or *, and you may group sub-expressions with parentheses in any way.
Your task is to find an expression that evaluates to goal. If several do, report the smallest one under the ordering defined below. If none do, report an empty string.
Rules
- Each number is used exactly once and in its original position. You may not reorder numbers, glue them into multi-digit numbers, or apply a unary minus.
- Exactly one operator sits between each pair of adjacent numbers. Division is not available. All arithmetic is exact integer arithmetic.
- Expressions are written in canonical form:
- A lone number is written as its decimal digits.
- Every binary operation is written as
(+ left part + operator + right part +), with no spaces. This includes the outermost operation. - An expression over
knumbers therefore contains exactlyk - 1pairs of parentheses. - Two different groupings are different strings, even if they have the same value.
- Among all canonical expressions whose value equals
goal, return the one that is smallest when compared character by character using ASCII codes. In this order(<)<*<+<-<0<1< ... <9. - If no canonical expression evaluates to
goal, return"".
Constraints
1 <= len(values) <= 60 <= values[i] <= 50-10^11 <= goal <= 10^11- Every intermediate and final value of every expression lies in
[-10^11, 10^11]. - If
len(values) == 1, the only expression is the number itself (no parentheses).
Examples
Example 1
Input: smallest_expression_for_goal([2, 3, 4], 14)
Output: '(2*(3+4))'
Example 2
Input: smallest_expression_for_goal([8, 3, 5, 2], 1)
Output: '((8+3)-(5*2))'
Example 3
Input: smallest_expression_for_goal([3, 3, 8], 3)
Output: ''
Hints
Hint 1
Choosing the parentheses is the same as choosing the last operation to be applied: it splits the list into a left block and a right block, each of which is an expression of the same kind.
Hint 2
For every contiguous interval of the list, compute all pairs (canonical string, value). Combine every split point, every left result, every right result and each of the three operators. Memoize per interval.
Hint 3
With at most 6 numbers there are only 42 * 3^5 = 10,206 expressions, so you can enumerate everything. Do not stop at the first match: collect every expression equal to the goal and keep the minimum string; Python string comparison already follows ASCII order.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Any way of placing operators and parentheses corresponds to a binary expression tree whose leaves are the numbers in order. The root of the tree is the last operation performed; it splits the interval values[i..j] at some index k, with the left subtree covering values[i..k] and the right subtree covering values[k+1..j].
This gives an interval recursion:
- For a single number, the only result is
(str(number), number). - For an interval of length at least 2, for each split
k, each left result(ls, lv), each right result(rs, rv)and each operator, produce("(" + ls + op + rs + ")", lv op rv).
We carry the canonical string and its exact value together, so nothing needs to be re-parsed or re-evaluated. Results are memoized per interval (i, j). At the top level, scan all results for the full list, keep those whose value equals goal, and return the smallest string (or "" if none).
Why it is correct
- Completeness: every canonical expression over two or more numbers has the shape
(A op B), whereAcovers a nonempty prefix andBthe remaining suffix. The recursion tries every split, every operator and every pair of sub-expressions, so every expression is generated. - No duplicates: the root split and operator are determined by the string, so each expression is generated exactly once.
- Format: leaves are bare digits and each binary node gets exactly one pair of parentheses and no spaces, so the strings match the required canonical form.
- Tie-break: Python compares strings by code point, which for these characters is exactly ASCII order. Taking the minimum over all matching strings gives the required answer.
Complexity
The number of expressions over n numbers is Catalan(n-1) * 3^(n-1), which is 10,206 for n = 6. Each string has length O(n).
- Time: O(E(n) * n) where
E(n)is that count, plus smaller contributions from sub-intervals. This is fine forn <= 6. - Space: O(E(n) * n) characters for the memoized results.
Reference solution
from typing import List
def smallest_expression_for_goal(values: List[int], goal: int) -> str:
n = len(values)
memo = {}
def build(i, j):
key = (i, j)
if key in memo:
return memo[key]
if i == j:
res = [(str(values[i]), values[i])]
else:
res = []
for k in range(i, j):
left = build(i, k)
right = build(k + 1, j)
for ls, lv in left:
for rs, rv in right:
res.append(("(" + ls + "+" + rs + ")", lv + rv))
res.append(("(" + ls + "-" + rs + ")", lv - rv))
res.append(("(" + ls + "*" + rs + ")", lv * rv))
memo[key] = res
return res
best = None
for s, v in build(0, n - 1):
if v == goal and (best is None or s < best):
best = s
return best if best is not None else ""