← Questions

Insert plus or minus signs between digits to reach a target

0
MetaCodingLast asked Dec 2025

A coding interview question asked in Meta's AI-enabled coding round, last asked Dec 2025. It tests backtracking and strings.

You get a string of digits and an integer target. Between each pair of adjacent digits you may insert +, -, or nothing (which joins the digits into a longer number). Digits stay in order, and none may be skipped. Return every expression that evaluates to target. A number may not have a leading zero, except the number 0 itself.

Interface

Unless you agree on a different interface with the interviewer, assume:

  • add_operators(digits: str, target: int) -> list[str] — the expressions in any order, with no spaces.

Example

digits = "123",  target = 6    ->  ["1+2+3"]
digits = "105",  target = 5    ->  ["10-5"]      # "1+0+5" is 6, and "05" is not a valid number
digits = "00",   target = 0    ->  ["0+0", "0-0"]
digits = "3",    target = 4    ->  []

Constraints

  • 1 <= len(digits) <= 12, so backtracking over every choice is acceptable.
  • -2^31 <= target <= 2^31 - 1.

Clarifying questions

  • Is the first number allowed to be negative (a leading -)? (No.)
  • Is multiplication allowed? (Not in this version.)
  • Are duplicates in the output possible, and should they be removed?
  • Is the output order important?

What a strong answer covers

  • Backtracking over the end position of the next number: at each step choose how many digits the next number takes, then whether it is added or subtracted.
  • Carrying the running value so the expression is never re-evaluated from scratch.
  • The leading-zero rule: once a number starts with 0, it must be exactly 0.
  • The cost: up to 3^(n-1) expressions, each O(n) to build, and why that is acceptable for n <= 12.
  • Tests: a single digit, digits that are all 0, a target no expression reaches, a large number formed from all digits.

Follow-ups

  • Allow * as well, with normal precedence. What extra state do you carry?
  • Return only the number of expressions that reach the target. Can you avoid building the strings?
  • Return the expression with the fewest operators.

Where it's asked

  • Meta · AI-enabled coding · Last asked Dec 202560 min · Several progressive tasks on a starter codebase in CoderPad with an AI assistant panel; usually two rounds · The first task usually without AI, later tasks with it

What it tests

backtracking · strings

Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding