Left-to-Right Plus/Times Expression from a Subsequence
Dynamic ProgrammingModel answerLast 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:
- A plain backtracking search that builds the subsequence while applying operators in left-to-right order.
- Pruning that speeds the search up (bounds on the running value, skipping equivalent states, early exit).
- A reverse search that starts at
targetand undoes the last operation using subtraction or exact division. When is each branch allowed, and in which order must elements be consumed? - Time and space complexity, including the worst case.
- 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.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Key observation
All numbers are at least 1, so with left-to-right evaluation the running value v never goes down: v + a > v and v * a >= v. Two consequences follow:
- Once a partial value exceeds
target, that branch is dead. Any element larger thantargetcan be ignored entirely. - The expression is just a fold:
v = first pick, thenv = v op next pick. We only need to track the current value, not the expression shape.
Assumption to state: a single chosen element with no operator is a valid expression, so target = 8 with 8 in A returns "8". I also assume target >= 1, and return false otherwise.
1. Backtracking baseline
dfs(i, v): for each later index j, either skip it, take v + A[j], or take v * A[j] (with A[j] as the starting value when nothing is chosen yet). Applying the operator immediately to the running value means precedence never arises. This explores up to O(3^n) paths, which is correct but exponential.
2. Pruning, which leads to a DP
- Value cap: drop any state with
v > target, which is safe by monotonicity. - Equivalent states: two different expressions over the same prefix that reach the same value have identical futures. Memoize on
(index, value). - Identity moves:
v * 1 = vcreates nothing new, so treat it as a skip. - Early exit: stop as soon as
targetappears.
Taking memoization to its conclusion gives a forward DP. Keep the set of values in [1, target] reachable from some subsequence of the processed prefix. Store a parent record (previous value, operator, number used) the first time a value appears, so an expression can be rebuilt.
Correctness is by induction on the prefix. A value reachable after processing A[i] is either A[i] alone or v op A[i] where v was reachable from the earlier prefix. Reconstruction works because a value's parent was created at a strictly earlier index, so following parents walks back through decreasing indices and yields a valid ordered subsequence.
3. Reverse search from the target
The last operator uses the last chosen element, so undo from the right. Define can(j, t) as "t can be built from a subsequence of A[0..j)":
can(j, t) = can(j-1, t) # skip A[j-1]
or A[j-1] == t # it is the only/first pick
or (t - A[j-1] >= 1 and can(j-1, t - A[j-1])) # undo '+'
or (A[j-1] > 1 and t % A[j-1] == 0
and can(j-1, t // A[j-1])) # undo '*'
Conditions:
- Subtraction: the remainder must stay at least 1. A remainder of exactly 0 would mean nothing precedes the element, which is the
A[j-1] == tbase case. - Division: only when
tis exactly divisible, because every intermediate value is an integer. Dividing by 1 changes nothing, so skip it. - Order: recursion only moves to smaller indices, so picks are consumed right to left, which keeps the subsequence order and single use.
Try division first, since it shrinks t fastest and often hits a base case sooner. Memoize on (j, t).
4. Complexity
Let R be the number of distinct reachable values at most target, so R <= min(target, 3^n).
- Forward DP:
O(n * R)time,O(R)space. - Plain backtracking:
O(3^n)time,O(n)space. - Worst case: the bound is pseudo-polynomial. With
targetnear2^31and many small elements,Rcan be huge. Using only+turns the task into subset sum, so no algorithm polynomial inlog(target)is expected. In that regime the reverse search is attractive, since divisibility removes most*branches and the memo collapses repeated(j, t)pairs.
5. Overflow and edge cases
- Cap before storing: test
v <= target - abefore adding andv <= target / abefore multiplying (integer division). In fixed-width languages, use 64-bit ints. Sincev <= target < 2^31anda < 2^31, a product stays below2^62. - Python does not overflow, but the cap still bounds the state count.
- Empty
Areturns false. Elements greater thantargetare skipped. - Runs of 1s:
*1is a no-op and+1just increments, which the dedup handles. - Duplicates are fine, since each position is its own candidate.
- A single element equal to
targetreturns just that number.
Code (forward DP with reconstruction)
from typing import List, Tuple
def find_expression(A: List[int], target: int) -> Tuple[bool, str]:
if target < 1:
return False, ""
# value -> (previous value or None, operator or None, number used)
parent = {}
for a in A:
if a > target:
continue
new = {}
if a not in parent:
new[a] = (None, None, a)
for v in parent: # only values from earlier elements
s = v + a
if s <= target and s not in parent and s not in new:
new[s] = (v, '+', a)
p = v * a
if p <= target and p not in parent and p not in new:
new[p] = (v, '*', a)
parent.update(new)
if target in parent:
break
if target not in parent:
return False, ""
tokens, v = [], target
while True:
prev, op, num = parent[v]
tokens.append(str(num))
if prev is None:
break
tokens.append(op)
v = prev
return True, "".join(reversed(tokens))
Iterating over parent while writing into new guarantees each element is used at most once per expression. On the sample input this returns a valid witness such as 1+9+8+7.
Follow-up pruning ideas
- Suffix upper bound: from value
vwith remaining suffixA[i:], the best reachable value is the fold ofmax(v + a, v * a). This is valid because each step is increasing inv. If that bound is belowtarget, prune. - Lower bound: the smallest continuation is
vitself (skip everything), so a state withv > targetis already dead. Also prune states that are too small relative to a remaining suffix bound. - Reverse and forward meet in the middle: compute reachable sets for the left half going forward and the right half going backward from
target, then intersect. - Bitset for small targets: when
targetis modest, represent reachable values as a bitset. The+astep becomes a shift, and*acan be done over set bits. - Collapse 1s: a run of 1s can only add 0 to
k, so treat the run as a single bounded increment. - Order by divisibility: in the reverse search, try divisors first and fail fast when
thas no usable factor in the remaining prefix.
Common mistakes
- Applying normal precedence, or building an expression tree when a running value suffices.
- Updating the reachable set in place so that one element is used twice.
- Forgetting that the remainder after subtraction must be at least 1.
- Dividing without an exact-divisibility check.
- Overflowing on
v * abefore comparing againsttarget.