Data Structures & AlgorithmsModerateTCS NQT Digital · Product Company SDE

Problem: Generate all subsets of a set of feature flags (backtracking) and count those whose sum equals a target.

Problem: Generate all subsets of a set of feature flags (backtracking) and count those whose sum equals a target.
def count(a, t, i=0):
    if i == len(a): return int(t == 0)
    return count(a, t - a[i], i + 1) + count(a, t, i + 1)
print(count([2, 3, 5, 7, 8], 10), count([], 0))
What is printed?
  1. A. 2 1
  2. B. 3 0
  3. C. 4 1
  4. D. 3 1

Correct answer: D. 3 1

Each element is either taken (subtract it from the target) or skipped: 2ⁿ leaves. Subsets summing to 10: {2, 8}, {3, 7}, {2, 3, 5}. For the empty list the only subset is the empty set, whose sum 0 matches, so 1 – not 0. O(2ⁿ).

More Coding Interview Problems questions

Exams that ask this topic