Zepruv › Coding problems

Expression Add Operators

Hard · Math, String, Backtracking

Given a string num that contains only digits and an integer target, return all possibilities to insert the binary operators '+', '-', and/or '*' between the digits of num so that the resultant expression evaluates to the target value.
Note that operands in the returned expressions should not contain leading zeros.
Note that a number can contain multiple digits.

Example 1

Input: num = "123", target = 6
Output: ["1*2*3","1+2+3"]

Both "1*2*3" and "1+2+3" evaluate to 6.

Example 2

Input: num = "232", target = 8
Output: ["2*3+2","2+3*2"]

Both "2*3+2" and "2+3*2" evaluate to 8.

Example 3

Input: num = "3456237490", target = 9191
Output: []

There are no expressions that can be created from "3456237490" to evaluate to 9191.

Constraints

Starter code (python)

class Solution(object):
    def addOperators(self, num, target):
        """
        :type num: str
        :type target: int
        :rtype: List[str]
        """
        

Related problems

Previous: Perfect Squares · Next: Find the Duplicate Number · All problems

Zepruv is a technical interview practice platform. Read any problem for free; sign in to run your code, submit and keep your progress.