Expression Add Operators (LeetCode 282): Solution and Explanation

Hard
Math
String
Backtracking

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.

Variables
No variables to display
DepthFunction Call
Stack empty
0/0

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

  1. Define backtrack(index, expr, value, prev), where expr is the expression built so far, value is its result and prev is the last signed term.
  2. When index reaches the end of num, record expr if value == target and return.
  3. Try every operand num[index:i+1] for i from index onward, and break as soon as the operand would have a leading zero.
  4. At index == 0 there is no operator to place, so recurse with the operand as both value and prev.
  5. 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).
  6. Start with backtrack(0, '', 0, 0) and return the collected expressions.

Step-by-step example

num = "123", target = 6
  1. 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.)
  2. 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).
  3. 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.
  4. From "1-2", the three options give 2, -4 and -1 - (-2) + (-6) = -5, so no match.
  5. From "1*2", operand "3": "1*2*3" computes 2 - 2 + 2 × 3 = 6, another match.
  6. 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 result

Time and space complexity

Time

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).

Space

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*3 into 9.
  • Storing prev as curr after a minus sign instead of -curr, which breaks expressions like 5-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.