Data Structures & AlgorithmsHardAmazon · Microsoft OA

Problem: Each candidate can be used at most ONCE and the list has duplicates; count the distinct combinations that sum to the target.

Problem: Each candidate can be used at most ONCE and the list has duplicates; count the distinct combinations that sum to the target.
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 i > start and c[i] == c[i-1]: continue
            if c[i] > rem: break
            go(i + 1, rem - c[i])
    go(0, t)
    return res
print(combos([2, 5, 2, 1, 2, 3], 5))
What is printed?
  1. A. 3
  2. B. 6
  3. C. 5
  4. D. 4

Correct answer: A. 3

Sorted: 1, 2, 2, 2, 3, 5. Distinct combinations: [1, 2, 2], [2, 3], [5]. Skipping equal siblings stops [1, 2, 2] from appearing 3 times (there are three 2s); without the skip the count would be larger.

More Coding Interview Problems questions

Exams that ask this topic