Construct Arithmetic Expression Matching Target
Dynamic ProgrammingAuto-graded · 27 test casesLast updated
Tests subset enumeration with bitmask DP, binary expression tree generation, operator application with exact rational arithmetic, and combinatorial search.
You are given a list of integers numbers and an integer goal. Your task is to determine whether you can construct an arithmetic expression that evaluates to exactly goal.
The rules are:
- You must choose at least one element from
numbers, and you may choose up to all of them. Each element may be used at most once in your expression. If multiple elements have the same value, they are still considered distinct elements (distinguished by their position in the array). - The elements you choose can be arranged in any order and combined using the four binary arithmetic operators: addition (
+), subtraction (-), multiplication (*), and division (/). You may use parentheses to group operations in any way. - All arithmetic is performed using exact rational numbers. Division is mathematical division (not integer division), so intermediate results may be fractions. No division by zero is permitted at any step of the computation.
- You cannot use unary operators (such as unary negation). You cannot concatenate the digits of different numbers to form a new number.
- An expression consisting of a single chosen number with no operators applied is valid. Therefore, if any element in
numbersequalsgoal, the answer istrue.
Return true if it is possible to form an expression that evaluates to exactly goal using the rules above. Otherwise, return false.
When comparing values, use exact equality with rational arithmetic—not floating-point approximation.
Constraints
1 <= numbers.length <= 50 <= numbers[i] <= 100-10^4 <= goal <= 10^4
Examples
Example 1
Input: build_expression_to_goal([1, 2, 3, 4], 24)
Output: True
Example 2
Input: build_expression_to_goal([3, 3, 8, 8], 24)
Output: True
Example 3
Input: build_expression_to_goal([2, 5], 9)
Output: False
Hints
Hint 1
Think of each expression as a binary tree: leaves hold numbers and internal nodes hold operators. The root operator splits your chosen numbers into two disjoint groups.
Hint 2
Represent subsets with bitmasks where each bit corresponds to an array index. For each subset, recursively compute all values reachable by splitting it into two non-empty parts.
Hint 3
Use Python's Fraction class for exact rational arithmetic. Floating-point numbers cannot reliably represent or compare fractional intermediate values.
Worked solution
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The core observation is that any arithmetic expression can be viewed as a binary tree. Each leaf contains a chosen number, and each internal node represents a binary operator combining the results of its left and right subtrees. The operator at the root divides the chosen numbers into two disjoint, non-empty groups.
We solve this using dynamic programming over bitmasks:
-
Bitmask representation: Each subset of array indices is represented as an integer bitmask. If bit
iis set, thennumbers[i]is included in that subset. -
Recursive value computation: For each subset (represented by a mask), we compute all possible values that can be achieved by expressions using exactly those elements. For a subset with one element, the only achievable value is that element itself. For larger subsets, we enumerate all ways to partition the subset into two non-empty parts, recursively compute achievable values for each part, and combine them using all four operators.
-
Partition enumeration: We iterate through all submasks of a given mask, keeping only one orientation of each unordered partition (using the condition
left_mask < right_mask). This avoids redundant work since we apply operators in both orders anyway. -
Operator application: For each pair of values from the two parts, we apply all four operators. For subtraction and division (non-commutative), we compute both
x op yandy op x. We skip division when the divisor is zero. -
Exact arithmetic: All computations use Python's
Fractionclass to maintain exact rational values. This is critical because intermediate results may be non-integer fractions, and we need exact equality when comparing to the target. -
Checking all subsets: Since we can use any non-empty subset of the input, we iterate through all possible masks from 1 to
2^n - 1and check whether the target appears in any reachable set.
Correctness
The algorithm is correct by structural induction:
- Base case: A single-element subset correctly produces only that element's value as a
Fraction. - Inductive step: For any expression tree using elements from a subset, the root operator partitions those elements into two disjoint non-empty parts. By the inductive hypothesis, we correctly compute all achievable values from each part. By trying all partitions and all operator combinations in both orders, we generate all possible expression values for that subset.
Division by zero is explicitly prevented by conditional checks. The use of exact rational arithmetic ensures that equality comparisons are precise.
Complexity
Time: Let n be the length of numbers (at most 5). The number of (mask, partition) pairs across all masks is O(3^n), which is roughly 243 for n = 5. For each partition, we perform a nested loop over achievable values from both parts. The size of these sets grows super-exponentially with subset size but remains tractable for n ≤ 5. In the worst case, there are approximately O(10^5) arithmetic operations involving Fraction objects.
Space: O(2^n × V), where V is the typical size of a reachable value set. We store one memoized set per non-empty subset. For n = 5, this means 31 sets, each potentially containing hundreds to thousands of Fraction objects in pathological cases.
from fractions import Fraction
from functools import lru_cache
from typing import List
def build_expression_to_goal(numbers: List[int], goal: int) -> bool:
n = len(numbers)
target = Fraction(goal)
@lru_cache(maxsize=None)
def compute_reachable(mask):
if mask & (mask - 1) == 0:
idx = mask.bit_length() - 1
return {Fraction(numbers[idx])}
values = set()
left_mask = (mask - 1) & mask
while left_mask:
right_mask = mask ^ left_mask
if left_mask < right_mask:
for x in compute_reachable(left_mask):
for y in compute_reachable(right_mask):
values.add(x + y)
values.add(x * y)
values.add(x - y)
values.add(y - x)
if y != 0:
values.add(x / y)
if x != 0:
values.add(y / x)
left_mask = (left_mask - 1) & mask
return values
all_bits = (1 << n) - 1
for current_mask in range(1, all_bits + 1):
if target in compute_reachable(current_mask):
return True
return False