Expression Add Operators - Problem
You are given a string of digits and a target number. Your mission is to transform this string into a valid mathematical expression by inserting the operators +, -, and * between the digits to make the expression evaluate to the target value.
The Challenge:
- You can split the digit string into multiple numbers (e.g., "123" can become "1", "2", "3" or "12", "3" or "1", "23", etc.)
- No leading zeros allowed in numbers (except for single digit "0")
- You must find all possible valid expressions that equal the target
- Operator precedence matters: multiplication happens before addition/subtraction
Example: Given num = "123" and target = 6, valid expressions include "1+2+3", "1*2*3", etc.
Input & Output
basic_case.py โ Python
$
Input:
num = "123", target = 6
โบ
Output:
["1+2+3", "1*2*3"]
๐ก Note:
Both expressions evaluate to 6: 1+2+3=6 and 1*2*3=6
complex_case.py โ Python
$
Input:
num = "232", target = 8
โบ
Output:
["2+3*2", "2*3+2"]
๐ก Note:
2+3*2 = 2+6 = 8 (multiplication first), and 2*3+2 = 6+2 = 8
edge_case.py โ Python
$
Input:
num = "105", target = 5
โบ
Output:
["1*0+5", "10-5"]
๐ก Note:
Valid expressions: 1*0+5=0+5=5 and 10-5=5. Note '05' is invalid due to leading zero
Visualization
Tap to expand
Understanding the Visualization
1
Initialize
Start with empty expression, sum=0, prev=0
2
Build Numbers
At each digit, decide to continue current number or start new one
3
Add Operators
When starting new number, try +, -, and * operators
4
Handle Precedence
For *, undo previous operation and multiply instead
5
Check Target
When string is consumed, check if sum equals target
Key Takeaway
๐ฏ Key Insight: By tracking the running sum and previous operand during backtracking, we can handle operator precedence efficiently without needing to parse and evaluate complete expressions. This reduces the time complexity significantly while maintaining correctness.
Time & Space Complexity
Time Complexity
O(4^n * n)
4^n possible expressions (3 operators + continue number at each position), n for evaluation
โ Linear Growth
Space Complexity
O(4^n)
Space to store all generated expressions
โก Linearithmic Space
Constraints
- 1 โค num.length โค 10
- num consists of only digits
- -231 โค target โค 231 - 1
- No leading zeros in operands except single digit '0'
- Return expressions in any order
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code