KatInterview

Left-to-Right Plus/Times Expression from a Subsequence

Dynamic ProgrammingModel answer
MediumModel answerDynamic Programmingdynamic-programmingbacktrackingpruning

Last updated

Decide whether a subsequence of positive integers, joined by + and * and evaluated strictly left to right, can equal a target, and produce one valid expression.

You are given an array A of positive 32-bit integers and an integer target. Pick some elements of A, keeping their original order and using each position at most once. Place + or * between each pair of neighbouring picks. The expression is evaluated strictly left to right with no operator precedence: start with the first number and apply each operator to the running total in turn.

For example, A = [1, 9, 8, 7, 10, 3, 1] and target = 25 is achievable with 8*3+1, since 8*3 = 24 and then 24+1 = 25. 1+9+8+7 also works.

Write a function that returns whether the target can be reached and, if so, one valid expression. State any assumption you make. For instance, decide whether a single chosen number with no operator counts as an expression.

Then discuss:

  1. A plain backtracking search that builds the subsequence while applying operators in left-to-right order.
  2. Pruning that speeds the search up (bounds on the running value, skipping equivalent states, early exit).
  3. A reverse search that starts at target and undoes the last operation using subtraction or exact division. When is each branch allowed, and in which order must elements be consumed?
  4. Time and space complexity, including the worst case.
  5. 32-bit overflow of intermediate values and other edge cases.

Follow-up: What further pruning ideas would you add?

Hints

Hint 1

Every number is at least 1, so the running value never decreases when you apply + or *. What does that let you do once the value exceeds the target?

Hint 2

Because evaluation is a left-to-right fold, the future of a partial expression depends only on the next index and the current value. Track the set of reachable values per prefix instead of whole expressions.

Hint 3

To go backwards from the target, the last operator involves the last chosen element. Undo it with t - a (keep the result at least 1) or t / a (only if exact), and move to a strictly smaller index.