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?- A. 3 6
- B. 3 1
- C. 3 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
- Problem: Compare the longest common SUBSTRING (contiguous) with the longest common SUBSEQUENCE of two log fragments. python def lcsub(a…
- Problem: Find the length of the shortest string that contains both a and b as subsequences: |a| + |b| − LCS(a, b). python def lcs(a, b)…
- Problem: Count the ways to roll n dice with k faces each so that the faces sum to target (mod 10⁹ + 7). python def dice(n, k, target…
- Problem: Picking a value v earns v points but deletes every v − 1 and v + 1 from the array; repeat until empty. Maximise points (reduces…
- Problem: Make two strings equal by deleting characters; the cost is the sum of ASCII codes of deleted characters. Minimise it (a weighted…
- Problem: Find the longest bitonic subsequence (strictly increasing then strictly decreasing; either part may be empty) using LIS from the…