Data Structures & AlgorithmsModerateInfosys SP/DSE · Product Company SDE

Problem: Generate all distinct subsets of a multiset of coupon values (skip equal values at the same recursion depth).

Problem: Generate all distinct subsets of a multiset of coupon values (skip equal values at the same recursion depth).
def subsets_dup(a):
    a.sort(); out = []
    def bt(i, path):
        out.append(path[:])
        for j in range(i, len(a)):
            if j > i and a[j] == a[j - 1]: continue
            path.append(a[j]); bt(j + 1, path); path.pop()
    bt(0, [])
    return out
r = subsets_dup([2, 1, 2, 2])
print(len(r), r[:5])
What is printed?
  1. A. 16 [[], [1], [1, 2], [1, 2, 2], [1, 2, 2, 2]]
  2. B. 6 [[], [1], [1, 2], [1, 2, 2], [1, 2, 2, 2]]
  3. C. 8 [[], [1], [2], [1, 2], [2, 2]]
  4. D. 8 [[], [1], [1, 2], [1, 2, 2], [1, 2, 2, 2]]

Correct answer: D. 8 [[], [1], [1, 2], [1, 2, 2], [1, 2, 2, 2]]

Distinct subsets of {1, 2, 2, 2}: choose 1 or not (2 ways) × how many 2s, 0..3 (4 ways) = 8, not 2⁴ = 16. Sorting groups equal values, and 'j > i and a[j] == a[j−1]' starts each branch with only the first copy at a given depth. Output is in DFS (preorder) order, so the first five go deeper along 1, 2, 2, 2 before backtracking. O(2ⁿ · n) worst case.

More Coding Interview Problems questions

Exams that ask this topic