KatInterview

Build an expression from 1 to 9 that hits a target

StringsAuto-graded · 24 test cases
MediumAuto-gradedStringsbacktrackingdfsrecursion

Last 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:

  1. 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.)
  2. At each gap between digits, try these choices in this order: +, then -, then concatenation with the previous term.
  3. Return the first complete expression that evaluates to target.

Expressions contain no spaces.

Constraints

  • target is any Python integer.
  • The digit string is always "123456789"; it is not an input.
  • Return type is Optional[str]: an expression string, or None.
  • Evaluate each candidate using the sign and value already tracked during the search. Do not call eval or 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.