Data Structures & AlgorithmsHardAmazon · Microsoft OA

Problem: Count the DISTINCT subsets (as multisets) of a list that contains duplicates, using backtracking that skips equal siblings.

Problem: Count the DISTINCT subsets (as multisets) of a list that contains duplicates, using backtracking that skips equal siblings.
def subsets(a):
    a.sort(); res = 0
    def go(i):
        nonlocal res
        res += 1
        for j in range(i, len(a)):
            if j > i and a[j] == a[j-1]: continue
            go(j + 1)
    go(0)
    return res
print(subsets([1, 2, 2, 3, 3]))
What is printed?
  1. A. 32
  2. B. 18
  3. C. 24
  4. D. 16

Correct answer: B. 18

A distinct multiset chooses 0–1 copies of 1, 0–2 copies of 2 and 0–2 copies of 3: 2 × 3 × 3 = 18 (including the empty set). Without the skip the code would list all 2⁵ = 32 index subsets.

More Coding Interview Problems questions

Exams that ask this topic