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?- A. 16 [[], [1], [1, 2], [1, 2, 2], [1, 2, 2, 2]]
- B. 6 [[], [1], [1, 2], [1, 2, 2], [1, 2, 2, 2]]
- C. 8 [[], [1], [2], [1, 2], [2, 2]]
- 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
- Problem: Produce the 3-bit Gray code sequence (consecutive codes differ in exactly one bit) with the formula g = i XOR (i >> 1). python…
- Problem: Trace the output of a recursive function that prints before and after its recursive call. python def walk(n): if n == 0: return…
- Problem: Sum the values of all LEFT leaves (leaves that are the left child of their parent). Trees are built from a level-order list by…
- Problem: Return (level, sum) of the level with the largest sum, levels numbered from 1 (smallest level on ties). Trees are built from a…
- Problem: Each root-to-leaf path spells a number (digits from root to leaf). Return the sum of these numbers. Trees are built from a…
- Problem: Split a string into pieces that are all palindromes and list every such partition (backtracking). python def palparts(s): res =…