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
INPUTnum = "232"target = 6232Need to insert +, -, *between digitsALGORITHM1Try all operator combinations2Handle multi-digit numbers3Track sum and precedence4Collect valid expressionsExamples:2+3+2 = 7 ❌2*3+0 = 6 ✓23-2 = 21 ❌RESULTValid Expressions:["2*3+0", "2+3+1"](example output)All expressions thatevaluate to target = 6Key Insight:Use backtracking with sum/last operand tracking to handle operator precedenceTutorialsPoint - Expression Builder | Optimized Backtracking
Asked in
Google 45 Facebook 38 Amazon 32 Microsoft 28
28.4K Views
Medium Frequency
~25 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen