KatInterview

Construct Arithmetic Expression Matching Target

Dynamic ProgrammingAuto-graded · 27 test cases
HardAuto-gradedDynamic Programmingbitmask-dprecursioncombinatorics

Last 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 numbers equals goal, the answer is true.

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 <= 5
  • 0 <= 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.