Expression Add Operators - Problem

Given a string num that contains only digits and an integer target, return all possibilities to insert the binary operators '+', '-', and/or '*' between the digits of num so that the resultant expression evaluates to the target value.

Note: Operands in the returned expressions should not contain leading zeros unless the operand is 0 itself. A number can contain multiple digits.

Input & Output

Example 1 — Basic Case
$ Input: num = "232", target = 8
Output: ["2*3+2", "2+3*2"]
💡 Note: 2*3+2 = 8 and 2+3*2 = 8. Both expressions evaluate to target 8.
Example 2 — Single Digit
$ Input: num = "3", target = 3
Output: ["3"]
💡 Note: Only one way: the number itself equals the target.
Example 3 — No Solution
$ Input: num = "123", target = 0
Output: []
💡 Note: No combination of +, -, * operators can make 123 digits equal 0.

Constraints

  • 1 ≤ num.length ≤ 10
  • num consists of only digits
  • -231 ≤ target ≤ 231 - 1

Visualization

Tap to expand
Expression Add Operators: "232" → 8232Insert operators: +, -, *Target: 82 * 3 + 2= 6 + 2 = 8 ✓2 + 3 * 2= 2 + 6 = 8 ✓2 + 3 + 2= 7 ≠ 8Valid Expressions: ["2*3+2", "2+3*2"]Return all expressions that evaluate to target
Understanding the Visualization
1
Input
String of digits and target number
2
Process
Try all ways to split digits and insert +, -, * operators
3
Output
All valid expressions that evaluate to target
Key Takeaway
🎯 Key Insight: Handle multiplication precedence by tracking the last operand separately during backtracking
Asked in
Google 15 Facebook 12 Amazon 8
180.0K Views
Medium Frequency
~25 min Avg. Time
1.8K 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