Data Structures & AlgorithmsVery hardProduct company OA

Problem: Insert '+', '−' or '' between the digits (or leave digits joined) so the expression equals the target. Operands may not have leading zeros. Multiplication is handled by undoing the last operand.

Problem: Insert '+', '−' or '*' between the digits (or leave digits joined) so the expression equals the target. Operands may not have leading zeros. Multiplication is handled by undoing the last operand.
def add_ops(num, target):
    res = []
    def bt(i, expr, val, last):
        if i == len(num):
            if val == target: res.append(expr)
            return
        for j in range(i + 1, len(num) + 1):
            s = num[i:j]
            if len(s) > 1 and s[0] == "0": break
            x = int(s)
            if i == 0: bt(j, s, x, x)
            else:
                bt(j, expr + "+" + s, val + x, x)
                bt(j, expr + "-" + s, val - x, -x)
                bt(j, expr + "*" + s, val - last + last * x, last * x)
    bt(0, "", 0, 0)
    return res
print(len(add_ops("2025", 7)), add_ops("105", 5))
What is printed?
  1. A. 3 ['1*0+5', '10-5', '1*05']
  2. B. 4 ['1+0*5', '1*0+5', '10-5']
  3. C. 2 ['1*0+5', '10-5']
  4. D. 3 ['1*0+5', '10-5']

Correct answer: D. 3 ['1*0+5', '10-5']

'last' is the signed value of the last multiplicative term, so val − last + last·x re-evaluates with correct precedence. "2025" = 7 via 2+0*2+5, 2−0*2+5, 2*0+2+5 → 3. For "105": 1*0+5 and 10−5; "1*05" is forbidden (leading zero) and 1+0*5 = 1. Search is O(4ⁿ) because each gap has 4 choices.

More Coding Interview Problems questions

Exams that ask this topic