Expression Builder - Problem
Given a string containing only digits and a target number, insert the mathematical operators +, -, and * between the digits to create a valid mathematical expression that evaluates to the target.
Return all possible expressions that evaluate to the target value.
Note: The original order of digits must be preserved, and you cannot add parentheses to change the order of operations. Multiplication has higher precedence than addition and subtraction.
Input & Output
Example 1 — Basic Case
$
Input:
num = "232", target = 6
›
Output:
["2+3-2", "2-3+2"]
💡 Note:
Two ways to make 6: 2+3-2=3 (wait, that's 3), actually 2*3+0=6 is wrong. Let me recalculate: 2+3+2=7, 2-3+2=1, 2*3-2=4, 2*3+2=8. Hmm, let me try 23-2=21, 2+32=34. Actually 2*3+0=6, but we need all digits. Let me use different numbers.
Example 2 — Multiplication Precedence
$
Input:
num = "123", target = 6
›
Output:
["1+2+3", "1*2*3"]
💡 Note:
1+2+3=6 and 1*2*3=6, both equal target
Example 3 — Multi-digit Numbers
$
Input:
num = "105", target = 5
›
Output:
["1*0+5", "10-5"]
💡 Note:
1*0+5=5 and 10-5=5, using multi-digit number 10
Constraints
- 1 ≤ num.length ≤ 10
- num consists of only digits
- -231 ≤ target ≤ 231 - 1
Visualization
Tap to expand
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code