Build Arithmetic Expressions That Hit a Target Value
Dynamic ProgrammingAuto-graded · 22 test casesLast updated
Tests backtracking with incremental precedence-aware evaluation to enumerate all +/* expressions over a number sequence that sum to a given target.
Problem Statement
You are given a sequence of non-negative integers digits and an integer goal. Between every consecutive pair of numbers in digits, place exactly one operator — either + or * — to form an arithmetic expression. Return every placement that makes the expression evaluate to goal.
Standard arithmetic precedence applies: multiplication is performed before addition. The original order of numbers must be preserved.
Return the valid expressions as a list of strings in lexicographical (ASCII) order. If no valid placement exists, return an empty list.
Rules and Clarifications
- Exactly one operator goes between each adjacent pair. No operator is placed before the first number or after the last.
- Evaluation follows standard precedence: consecutive multiplications form a product block, and those blocks are summed together. For example,
1+2*3*4evaluates as1 + (2*3*4) = 25. - When a single number is provided, no operators can be inserted. Return
[str(digits[0])]if that number equalsgoal, otherwise return[]. - In ASCII encoding,
'*'(code 42) sorts before'+'(code 43), so expressions with*at an earlier position appear first in the output.
Constraints
1 <= len(digits) <= 160 <= digits[i] <= 100-2^31 <= goal <= 2^31 - 1
Examples
Example 1
Input: build_target_expressions([1, 2, 3, 4], 11)
Output: ['1+2*3+4']
Example 2
Input: build_target_expressions([2, 3, 2], 8)
Output: ['2*3+2', '2+3*2']
Hints
Hint 1
There are at most 2^15 = 32,768 operator combinations for the maximum input length, so exhaustive search over all placements is fast enough — no pruning is required to pass within time limits.
Hint 2
Evaluating each expression from scratch would be expensive. Instead, carry two numbers through the recursion: the sum of all fully closed product blocks so far, and the value of the product block currently being extended. When you place '+', the open block closes and a new one starts; when you place '*', the open block grows.
Hint 3
When the recursion reaches the last number, the final expression value is simply (closed sum) + (open product block). Sort the collected strings before returning to guarantee ASCII order.
Worked solution
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Why exhaustive search is viable
With at most 16 numbers there are at most 15 operator slots, giving 2^15 = 32,768 candidate expressions. Visiting all of them is negligible work for modern hardware, so the right strategy is a depth-first enumeration that branches on + and * at every slot.
Handling operator precedence incrementally
The only subtlety is evaluating each expression efficiently without rebuilding or re-parsing it. An expression under standard precedence is always a sum of product blocks: consecutive numbers joined by * form one block, and + separates blocks. For example:
2 + 3 * 5 * 4 + 1 = 2 + (3*5*4) + 1 = 63
We track two values through the recursion:
closed_sum— the sum of every product block that has already been fully closed by a+.open_block— the running product of the block currently being extended.
At each step, placing an operator updates the state:
| Operator placed | New closed_sum | New open_block |
|---|---|---|
+ | closed_sum + open_block | next_value |
* | closed_sum (unchanged) | open_block * next_value |
When we reach the end of digits, the complete expression's value is closed_sum + open_block.
Correctness
By induction, closed_sum + open_block always equals the standard-precedence value of the prefix built so far. * extends only the open block, exactly mirroring how multiplication binds tighter. + finalises that block and never revisits it. Every one of the 2^(n-1) operator assignments is visited exactly once, so the enumeration is both complete and non-redundant.
Ordering
After collecting all valid expressions we call results.sort(). Because the numbers occupy the same positions in every expression, two strings first differ at an operator character. '*' (ASCII 42) sorts before '+' (ASCII 43), so lexicographic order naturally places *-first expressions ahead of +-first ones at the same slot.
Edge cases
- Single number:
searchstarts at index 1, which immediately equalslen(digits). The checkclosed_sum + open_block == goalreduces todigits[0] == goal. - Zero in
digits:open_block * 0 = 0zeroes only the current open block;closed_sumfrom earlier+placements is untouched.5+3*0correctly evaluates to 5. - Negative target: all values are non-negative, so no expression can match; the result list stays empty.
- Large products: Python uses arbitrary-precision integers, so values like
100^16cause no overflow.
Complexity
- Time:
O(2^(n-1) · n)—2^(n-1)leaves, each requiringO(n)work to build the expression string. - Space:
O(n)recursion depth and current string, plusO(k · n)for thekvalid results stored.
Reference solution
from typing import List
def build_target_expressions(digits: List[int], goal: int) -> List[str]:
if not digits:
return []
results = []
def search(index, closed_sum, open_block, expr):
# closed_sum : sum of all fully completed product blocks
# open_block : value of the product block still being extended
if index == len(digits):
if closed_sum + open_block == goal:
results.append(expr)
return
value = digits[index]
text = str(value)
# Place '+': close the open block, start a fresh one
search(index + 1, closed_sum + open_block, value, expr + "+" + text)
# Place '*': extend the open block
search(index + 1, closed_sum, open_block * value, expr + "*" + text)
search(1, 0, digits[0], str(digits[0]))
results.sort()
return results