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?- A. 3 ['1*0+5', '10-5', '1*05']
- B. 4 ['1+0*5', '1*0+5', '10-5']
- C. 2 ['1*0+5', '10-5']
- 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
- Problem: A thief robs houses arranged as a binary tree; robbing two directly linked houses triggers an alarm. Each node returns (best if…
- Problem: Place the minimum number of cameras on tree nodes so every node is monitored (a camera covers itself, its parent and its…
- Problem: A tree of n nodes holds n coins in total, unevenly. A move transfers one coin between adjacent nodes. Minimum moves so every node…
- Problem: Return all node values at exactly distance k from a target node (distance counts edges, moving up or down). Record parent…
- Problem: Rocks are smashed repeatedly: take the two heaviest; if equal both vanish, otherwise the difference remains. Report the last…
- Problem: Room 0 is open; each room holds keys to other rooms. Can every room be visited? (DFS over keys.) python def canvisitall(rooms)…