Data Structures & AlgorithmsModerateTCS NQT Digital · Product Company SDE

Problem: Count subsets of distinct-position items whose values sum exactly to the target (0/1 counting knapsack with a 1-D array iterated downwards).

Problem: Count subsets of distinct-position items whose values sum exactly to the target (0/1 counting knapsack with a 1-D array iterated downwards).
def count_subsets(a, t):
    dp = [1] + [0] * t
    for x in a:
        for s in range(t, x - 1, -1):
            dp[s] += dp[s - x]
    return dp[t]
print(count_subsets([2, 3, 5, 6, 8], 8), count_subsets([1, 1, 1, 1], 2))
What is printed?
  1. A. 3 6
  2. B. 3 1
  3. C. 3 4
  4. D. 4 6

Correct answer: A. 3 6

dp[s] = number of subsets of the items seen so far with sum s; iterating s downwards uses each item at most once. Target 8: {8}, {2, 6}, {3, 5} → 3. The four 1s are different items, so choosing any two gives C(4, 2) = 6. Iterating s upwards would reuse items (unbounded) and overcount. O(n · t).

More Coding Interview Problems questions

Exams that ask this topic