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?- A. 2 1
- B. 3 0
- C. 4 1
- 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
- Problem: Generate all permutations of a list that may contain duplicates, without repeats. How many are produced? python def perms(a)…
- Problem: Generate all valid strings of n pairs of brackets in lexicographic order of the recursion ('(' tried first). python def gen(n)…
- Problem: Count the ways to place n queens on an n × n board so none attack each other. python def queens(n): cols, d1, d2 = set(), set()…
- Problem: Find whether a word exists in a letter grid by moving to adjacent (up/down/left/right) cells without reusing a cell. python def…
- Problem: List all combinations of k numbers from 1..n that sum to s (each number used at most once). python def combo(k, s, n=9): out = []…
- Problem: The recursive function below counts calls. How many times is f called for f(5)? python calls = 0 def f(n): global calls calls +=…