Expression Add Operators

Hard · Backtracking · Math · String · Backtracking

Problem

You are given a string num of digits and an integer target. Between neighboring digits you may put +, -, * or nothing at all; nothing joins the digits into a longer number. The expression is evaluated with the usual precedence: * before + and -.

Return every expression that evaluates to target, in any order. The digits stay in their order, and no operand may have a leading zero: "05" is not allowed, although "0" alone is.

Examples

Input: num = "124", target = 9
Output: ["1+2*4"]

1 + 2 * 4 = 9, and no other placement gives 9.

Input: num = "105", target = 5
Output: ["1*0+5","10-5"]

1 * 0 + 5 and 10 - 5 both make 5; 1 * 05 is not allowed because of the leading zero.

Input: num = "11", target = 3
Output: []

The only values reachable are 2, 0, 1 and 11.

Constraints

Approaches

Follow-up

What if you only need the number of expressions, not the expressions themselves? Building the strings is most of the memory traffic; count instead. The search space is still about 4^(n-1), because the value and last term rarely repeat, so memoization helps little; the problem is exponential by nature.

Related problems

Start free on Cariara · Coding problems · System design studio

Starting Python
No results yet.

          
↑↓ move ↵ open esc close

Labs

Loading labs…

Run with your own input

Starting Python

Loading Python…