KatInterview

Build Arithmetic Expressions That Hit a Target Value

Dynamic ProgrammingAuto-graded · 22 test cases
HardAuto-gradedDynamic Programmingbacktrackingrecursionoperator-precedence

Last 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*4 evaluates as 1 + (2*3*4) = 25.
  • When a single number is provided, no operators can be inserted. Return [str(digits[0])] if that number equals goal, 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) <= 16
  • 0 <= 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.