Expression Add Operators (LeetCode 282): Solution and Explanation
Given a string of digits and a target number, insert +, - or * between digits (or nothing, which joins digits into a longer number) and return every expression that evaluates to the target. Operands may not have leading zeros.
Watch it run step by step
Try your own input and write the code →Intuition
Between each pair of adjacent digits there are four choices: one of three operators or no operator at all. A string of n digits therefore produces up to 4^(n-1) expressions, and since the digit string is at most 10 characters in the usual constraints, exhaustive search is exactly what we want. The only question is how to evaluate expressions cheaply while we build them, instead of generating a full string and parsing it at the end.
Addition and subtraction are easy to evaluate incrementally: keep a running value and add or subtract the next operand. Multiplication is the problem, because it binds tighter. If the running expression is 1 + 2 with value 3 and we append * 3, the right answer is 1 + 6 = 7, not 3 × 3 = 9.
The fix is to remember prev, the signed value of the last term that was added to the running total. When we multiply by curr, we first undo that term with value - prev, then add the new combined term prev * curr. The new prev becomes prev * curr, so a chain like 2 * 3 * 4 keeps working. For subtraction we store prev as -curr, which makes the undo step correct even after a minus sign.
Leading zeros are the remaining rule. An operand can be "0" but never "05", so when the first digit of a candidate operand is 0 we stop extending it after one digit.
Approach: Backtracking with a running value and last operand
- Define
backtrack(index, expr, value, prev), whereexpris the expression built so far,valueis its result andprevis the last signed term. - When
indexreaches the end ofnum, recordexprifvalue == targetand return. - Try every operand
num[index:i+1]forifromindexonward, and break as soon as the operand would have a leading zero. - At
index == 0there is no operator to place, so recurse with the operand as bothvalueandprev. - Otherwise recurse three times: with
+(value plus curr, prev = curr), with-(value minus curr, prev = -curr) and with*(value - prev + prev * curr, prev = prev * curr). - Start with
backtrack(0, '', 0, 0)and return the collected expressions.
Step-by-step example
num = "123", target = 6
- Index 0 takes operand "1", giving expr "1", value 1, prev 1. (Operands "12" and "123" are also tried, and none of their expressions reach 6.)
- From "1", operand "2" yields "1+2" (value 3, prev 2), "1-2" (value -1, prev -2) and "1*2" (value 1 - 1 + 2 = 2, prev 2).
- From "1+2", operand "3": "1+2+3" has value 6, a match. "1+2*3" computes 3 - 2 + 6 = 7, which correctly respects precedence.
- From "1-2", the three options give 2, -4 and -1 - (-2) + (-6) = -5, so no match.
- From "1*2", operand "3": "1*2*3" computes 2 - 2 + 2 × 3 = 6, another match.
- The result is ["1+2+3", "1*2*3"].
Code: Python, Java, C++
1class Solution:
2 def addOperators(self, num: str, target: int) -> List[str]:
3 result = []
4
5 def backtrack(index, expr, value, prev):
6 if index == len(num):
7 if value == target:
8 result.append(expr)
9 return
10
11 for i in range(index, len(num)):
12 # Skip numbers with leading zeros
13 if i > index and num[index] == '0':
14 break
15
16 curr_str = num[index:i+1]
17 curr = int(curr_str)
18
19 if index == 0:
20 backtrack(i + 1, curr_str, curr, curr)
21 else:
22 backtrack(i + 1, expr + '+' + curr_str, value + curr, curr)
23 backtrack(i + 1, expr + '-' + curr_str, value - curr, -curr)
24 backtrack(i + 1, expr + '*' + curr_str, value - prev + prev * curr, prev * curr)
25
26 backtrack(0, '', 0, 0)
27 return result1class Solution {
2 public List<String> addOperators(String num, int target) {
3 List<String> result = new ArrayList<>();
4 backtrack(num, target, 0, "", 0, 0, result);
5 return result;
6 }
7
8 private void backtrack(String num, int target, int index, String expr, long value, long prev, List<String> result) {
9 if (index == num.length()) {
10 if (value == target) result.add(expr);
11 return;
12 }
13
14 for (int i = index; i < num.length(); i++) {
15 if (i > index && num.charAt(index) == '0') break;
16
17 String currStr = num.substring(index, i + 1);
18 long curr = Long.parseLong(currStr);
19
20 if (index == 0) {
21 backtrack(num, target, i + 1, currStr, curr, curr, result);
22 } else {
23 backtrack(num, target, i + 1, expr + "+" + currStr, value + curr, curr, result);
24 backtrack(num, target, i + 1, expr + "-" + currStr, value - curr, -curr, result);
25 backtrack(num, target, i + 1, expr + "*" + currStr, value - prev + prev * curr, prev * curr, result);
26 }
27 }
28 }
29}1class Solution {
2public:
3 vector<string> addOperators(string num, int target) {
4 vector<string> result;
5 backtrack(num, target, 0, "", 0, 0, result);
6 return result;
7 }
8
9private:
10 void backtrack(const string& num, int target, int index, string expr, long value, long prev, vector<string>& result) {
11 if (index == num.size()) {
12 if (value == target) result.push_back(expr);
13 return;
14 }
15
16 for (int i = index; i < num.size(); i++) {
17 if (i > index && num[index] == '0') break;
18
19 string currStr = num.substr(index, i - index + 1);
20 long curr = stol(currStr);
21
22 if (index == 0) {
23 backtrack(num, target, i + 1, currStr, curr, curr, result);
24 } else {
25 backtrack(num, target, i + 1, expr + "+" + currStr, value + curr, curr, result);
26 backtrack(num, target, i + 1, expr + "-" + currStr, value - curr, -curr, result);
27 backtrack(num, target, i + 1, expr + "*" + currStr, value - prev + prev * curr, prev * curr, result);
28 }
29 }
30 }
31};Time and space complexity
O(n × 4^n)
Each of the n - 1 gaps has four choices, so there are O(4^n) expressions, and building each expression string costs up to O(n).
O(n)
The recursion depth is at most n and each frame holds an expression of length O(n). The output list itself is not counted.
Other approaches
Generate all expressions, then evaluate (time O(n × 4^n), space O(n × 4^n))
Enumerate every operator placement as a string and evaluate each one with a stack-based parser. It is easier to get right at first but repeats the evaluation work for shared prefixes, so it is noticeably slower.
Common mistakes
- Multiplying the whole running value by the new operand, which ignores precedence and turns
1+2*3into 9. - Storing
prevascurrafter a minus sign instead of-curr, which breaks expressions like5-2*3. - Allowing operands such as "05", which the problem forbids. The loop must break once it extends past a leading zero.
- Using 32-bit integers in Java or C++. Operands of ten digits and products of them overflow, so use 64-bit longs.
Frequently asked questions
Why do we need the prev variable?
Multiplication must apply only to the last term, not the whole running total. Keeping prev lets us subtract that last term and add back its product with the new operand, which evaluates the expression correctly in one pass.
How are numbers with leading zeros handled?
A single "0" is a valid operand, but anything longer that starts with 0 is not. The loop breaks as soon as i > index and num[index] == '0'.
Can Expression Add Operators be solved with dynamic programming?
Not usefully, because the problem asks for every expression, not a count. The output itself can be exponential, so backtracking that evaluates as it goes is the standard and expected solution.