Menu

Sign in to track your progress and unlock all features.

Theme style

Log in

Full lesson preview

Generate all valid expressions to reach a target

Insert operators (+, -, *) between digits of a number string to generate expressions that evaluate to a target value.

Python practice34 minRecursion & BacktrackingAdvancedLast updated March 27, 2026

Problem statement

Given a string num that contains only digits and an integer target, return all possible strings that can be built by inserting binary operators '+', '-', or '*' between the digits so that the resulting expression evaluates to the target value. Do not reorder digits. Numbers in the expression must not have leading zeros unless the number is exactly '0'. Use recursion to explore possibilities, tracking the current evaluated value and the previous operand value to correctly handle multiplication precedence.

Task

Practice recursive enumeration and handling operator precedence (multiplication) and constraints like no leading zeros.

Examples

Example 1

Input

add_operators('123', 6)

Output

['1+2+3', '1*2*3']

'1+2+3' and '1*2*3' both evaluate to 6.

Input format

Two arguments: a string num of digits and an integer target.

Output format

A list of expression strings that evaluate to target. Each expression uses the original digits in order and inserted operators. Example: ['1+2+3', '1*2*3']

Constraints

1 <= len(num) <= 12. Avoid building numbers with leading zeros (skip multi-digit segments starting with '0'). Use recursion and pass along the current computed value and previous operand (for multiplication handling).

Samples

Sample 1

Input

add_operators('105', 5)

Output

['1*0+5', '10-5']

Two expressions evaluate to 5: '1*0+5' and '10-5'.