Data Structures & AlgorithmsHardProduct company OA
Problem: Find all combinations of unlimited-use stamp values that total exactly 15 (each combination listed once, in non-decreasing order).
Problem: Find all combinations of unlimited-use stamp values that total exactly 15 (each combination listed once, in non-decreasing order).
def comb_sum(cands, target):
res = []
def bt(i, rem, path):
if rem == 0: res.append(path[:]); return
for j in range(i, len(cands)):
if cands[j] > rem: break
path.append(cands[j]); bt(j, rem - cands[j], path); path.pop()
bt(0, target, [])
return res
r = comb_sum([3, 4, 5], 15)
print(len(r), r[1])What is printed?- A. 3 [3, 3, 4, 5]
- B. 4 [3, 4, 4, 4]
- C. 4 [3, 3, 4, 5]
- D. 6 [3, 3, 4, 5]
Correct answer: C. 4 [3, 3, 4, 5]
Recursing with bt(j, …) (not j + 1) allows reuse, and never going back to smaller indices avoids permutations of the same multiset. Combinations: 3×5, 3+3+4+5, 3+4+4+4, 5×3 → 4. Counting ordered sequences would give many more. The 'break' prunes because the candidates are sorted.
More Coding Interview Problems questions
- Problem: Restore all valid IPv4 addresses from a digit string (four parts, each 0–255, no leading zeros except "0"). python def…
- Problem: Return every value an arithmetic expression can take under all possible full parenthesisations (divide and conquer on each…
- Problem: A node is 'good' if no node on the path from the root to it has a greater value. Count good nodes. Trees are built from a…
- Problem: Exactly two keys of a BST were swapped by mistake. Find them with an inorder traversal: the first key is the left side of the…
- Problem: Trim a BST so that only keys in [lo, hi] remain (keeping BST structure), then print its preorder. Trees are built from a…
- Problem: Rebuild a BST from its preorder in O(n) using an upper bound per recursive call, then print its postorder and height (nodes on…