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 INPUT String: num = "232" 2 idx 0 3 idx 1 2 idx 2 target = 8 Available Operators: + - * join Insert between digits: 2 _ 3 _ 2 4 choices x 4 choices = 16 combinations ALGORITHM STEPS 1 Backtracking DFS Explore all operator placements 2 Track State curr_val, prev_operand for * 3 Handle * Priority Undo prev, apply * first 4 Check at End If value == target, add result Decision Tree (partial): 2 +3 -3 *3 5 -1 6 +2=7 *2=8 +2=8 *2=12 FINAL RESULT Valid Expressions Found: "2*3+2" 2*3+2 = 6+2 = 8 "2+3*2" 2+3*2 = 2+6 = 8 OUTPUT: ["2*3+2", "2+3*2"] OK - 2 solutions Rejected: 2+3+2=7, 2-3+2=1 2*3*2=12, 2-3*2=-4, etc. Key Insight: For multiplication priority, track the previous operand. When applying *, undo the previous addition/subtraction and recalculate: new_val = curr - prev + (prev * num). This handles operator precedence without building/parsing the full expression. Time: O(4^n * n) TutorialsPoint - Expression Add Operators | Optimal Backtracking Solution
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