Data Structures & AlgorithmsVery hardGoldman Sachs OA · LeetCode medium-hard

Problem: Insert +, − or between the digits of num (or leave digits joined) so that the expression equals target. Count the expressions (no operand may have a leading zero).

Problem: Insert +, − or * between the digits of num (or leave digits joined) so that the expression equals target. Count the expressions (no operand may have a leading zero).
def count(num, target):
    res = 0
    def go(i, val, last):
        nonlocal res
        if i == len(num):
            res += val == target; 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: go(j, x, x)
            else:
                go(j, val + x, x); go(j, val - x, -x)
                go(j, val - last + last * x, last * x)
    go(0, 0, 0)
    return res
print(count("2322", 10))
What is printed?
  1. A. 1
  2. B. 3
  3. C. 2
  4. D. 4

Correct answer: D. 4

Tracking the last operand lets '*' undo it: val − last + last·x respects precedence. For '2322' and 10 the expressions are 2+3*2+2, 2*3+2+2, 2*3+2*2 and 2*3*2-2: 4 in all, matching a brute force over all 4³ operator choices. Evaluating strictly left to right would accept wrong ones such as 2+3*2-… and miss precedence.

More Coding Interview Problems questions

Exams that ask this topic