oneby7

Recursion and Backtracking Searching with constraints

337. Expression Add Operators

Hard

You are given a string num of digits and an integer target. In each gap between two neighbouring digits, you may put one of the operators +, - and *, or nothing. Return every expression made this way whose value is target.

Digits with nothing between them join into one number, so 12+3 holds the numbers 12 and 3. A number of two or more digits cannot start with 0: 1*05 is not allowed, but 1*0+5 is. No operator goes in front of the first digit, and the digits stay in their order.

The value is calculated with the usual rules: * comes before + and -, and operators at the same level are applied from left to right. So 2+3*4 is 14.

Write each expression as a string with no spaces. The expressions can come back in any order, and any order is accepted. The examples sort them. If no expression works, return an empty list, [].

Example 1

Input: num = "8756", target = 57

Output: ["8*7-5+6","8-7+56","87-5*6"]

Explanation: 8*7-5+6 is 56 − 5 + 6. 8-7+56 joins 5 and 6 into 56. In 87-5*6 the * comes first, so it is 87 − 30.

Example 2

Input: num = "100", target = 0

Output: ["1*0*0","1*0+0","1*0-0","10*0"]

Explanation: A single 0 is a number, so 1*0+0 counts. 1*00 does not, because 00 starts with a zero.

Example 3

Input: num = "4096", target = 4096

Output: ["4096"]

Explanation: Putting no operator anywhere is allowed too. Then all of num is one number.

Check your understanding

Work out the answer for this input before you write any code.

num = "123", target = 9

Constraints

  • 1 ≤ num.length ≤ 10
  • num holds only the digits 0 to 9.
  • -231 ≤ target ≤ 231 − 1

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.