Data Structures & AlgorithmsHardAmazon · Microsoft OA
Problem: Count the combinations (multisets) of candidates that sum to the target; each candidate may be used any number of times.
Problem: Count the combinations (multisets) of candidates that sum to the target; each candidate may be used any number of times.
def combos(c, t):
c.sort(); res = 0
def go(start, rem):
nonlocal res
if rem == 0: res += 1; return
for i in range(start, len(c)):
if c[i] > rem: break
go(i, rem - c[i])
go(0, t)
return res
print(combos([3, 4, 5, 7], 15))What is printed?- A. 4
- B. 9
- C. 7
- D. 6
Correct answer: D. 6
Passing i (not i + 1) allows reuse, and never going back below start avoids counting 3+5+7 and 7+5+3 separately. The combinations are 3+5+7, 4+4+7, 5+5+5, 3+3+4+5, 3+4+4+4 and 3+3+3+3+3: 6 in all.
More Coding Interview Problems questions
- Problem: AND of every integer in the range [lo, hi]. python def rangeand(lo, hi): shift = 0 while lo != hi: lo >>= 1; hi >>= 1; shift += 1…
- Problem: Ugly numbers have no prime factors other than 2, 3 and 5. Generate them in order with three pointers. python def ugly(n): u =…
- Problem: Convert a fraction to a decimal string, putting a repeating part in parentheses. python def frac(n, d): q, r = divmod(n, d); s =…
- Generating all permutations of n distinct items with backtracking and copying each complete permutation into the result list costs how…
- A disjoint-set forest uses path compression but NO union by rank/size. What is its amortised cost per operation over m operations on n…
- What is the running time of Dijkstra's algorithm with a Fibonacci heap on a graph with V vertices and E edges?