Build an expression from 1 to 9 that hits a target
StringsAuto-graded · 24 test casesLast updated
Tests depth-first backtracking over operator choices, on-the-fly evaluation without re-parsing, and deterministic tie-breaking when several valid answers exist.
Problem
Take the fixed digit string "123456789". Between each pair of adjacent digits you may insert one of three things: a +, a -, or nothing at all (which joins the two digits into one multi-digit number). You may also place a - in front of the very first digit. Every resulting expression is evaluated with ordinary + and - (no multiplication, and the usual left-to-right sum of signed terms).
Given an integer target, return the expression that evaluates to target, or None if no expression does.
When several expressions work, return the one that your search finds first, using this procedure:
- Try the leading sign options in this order: no sign, then a leading
-. (A leading+gives the same values as no sign, so it is never needed.) - At each gap between digits, try these choices in this order:
+, then-, then concatenation with the previous term. - Return the first complete expression that evaluates to
target.
Expressions contain no spaces.
Constraints
targetis any Python integer.- The digit string is always
"123456789"; it is not an input. - Return type is
Optional[str]: an expression string, orNone. - Evaluate each candidate using the sign and value already tracked during the search. Do not call
evalor re-parse the string for each candidate. - Assume the total number of candidate expressions is small (at most a few thousand), so an exhaustive depth-first search is acceptable.
Examples
Example 1
Input: find_digit_expression(45)
Output: '1+2+3+4+5+6+7+8+9'
Example 2
Input: find_digit_expression(100)
Output: '1+2+3-4+5+6+78+9'
Example 3
Input: find_digit_expression(123456789)
Output: '123456789'
Example 4
Input: find_digit_expression(-1)
Output: '1+2+3+4+5-6+7-8-9'
Hints
Hint 1
Think of the search as choosing, for each of the 8 gaps, one of three actions, plus one choice for the leading sign. Explore them in the order the procedure specifies so the first hit is the answer.
Hint 2
Track the running total and the value of the last term separately. Concatenating a digit onto the last term means replacing that term with term*10 + digit (keeping its sign), and adjusting the total by the difference.
Hint 3
Because the search is ordered and returns the first success, once a branch returns a result you can stop immediately. Remember that a leading '+' produces the same values as no sign, so skipping it does not change the answer.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The search space is the set of ways to fill the 8 gaps between digits, each with one of three actions (+, -, or concatenate), times 2 leading-sign options. That is at most 2 · 3^8 = 13,122 expressions.
A recursive DFS walks the digits from left to right. It carries three pieces of state:
total: the value of all completed terms plus the current, still-open term.last_term: the signed value of the current open term, so concatenation can extend it.expr: the string built so far.
At each position the DFS tries the three actions in the required order:
+starts a new term with value+d, so the total gainsd.-starts a new term with value-d, so the total losesd.- Concatenate replaces the open term
twithsign(t) · (|t|·10 + d). The total becomestotal - t + new_term.
When all digits are consumed, the DFS compares total with target. Because the first success is returned, and the branches are tried in a fixed order, the output matches the required tie-break.
The outer loop tries the leading sign options "" and then "-". A leading + is skipped. It produces the same values as "", so if "" finds nothing, "+" would not either.
Why it is correct
- Complete enumeration: every combination of gap actions and leading sign is visited exactly once, so no valid expression is missed.
- Correct evaluation: the signed-term state gives the same value as evaluating the expression left to right. Concatenation preserves the sign of the term it extends, which matches how
-12is read as one negative term. - Deterministic output: the branch order and the leading-sign order are fixed, so the first success is well defined and matches the expected answer.
Complexity
- Time: O(3^n) nodes for n = 9 digits, about 13,000 leaves, with O(1) arithmetic per node. Building the string costs O(n) per returned answer, and string concatenation in the recursion adds at most a small constant factor.
- Space: O(n) recursion depth. The expression strings are created per call, so the peak extra space is O(n²) characters in the worst case, which is negligible at n = 9.
Python integers are arbitrary precision, so no overflow handling is needed. Because the digit string is short and fixed, the search is fast even without pruning.
from typing import Optional
def find_digit_expression(target: int) -> Optional[str]:
digits = "123456789"
def dfs(pos, total, last_term, expr):
if pos == len(digits):
return expr if total == target else None
d = int(digits[pos])
text = digits[pos]
# Choice 1: start a new term with '+'
result = dfs(pos + 1, total + d, d, expr + "+" + text)
if result is not None:
return result
# Choice 2: start a new term with '-'
result = dfs(pos + 1, total - d, -d, expr + "-" + text)
if result is not None:
return result
# Choice 3: concatenate onto the previous term, keeping its sign
sign = -1 if last_term < 0 else 1
extended = sign * (abs(last_term) * 10 + d)
return dfs(pos + 1, total - last_term + extended, extended, expr + text)
for lead in ("", "-"):
first = int(digits[0])
if lead == "-":
first = -first
result = dfs(1, first, first, lead + digits[0])
if result is not None:
return result
return None