Data Structures & AlgorithmsModerateInfosys SP/DSE · Product Company SDE
Problem: Enumerate all subsets of a small item list using bitmasks and count subsets with even sum.
Problem: Enumerate all subsets of a small item list using bitmasks and count subsets with even sum.
a = [3, 4, 5, 6]
cnt = 0
for mask in range(1 << len(a)):
s = sum(a[i] for i in range(len(a)) if mask >> i & 1)
cnt += s % 2 == 0
print(cnt, 1 << len(a))What is printed?- A. 7 16
- B. 8 15
- C. 9 16
- D. 8 16
Correct answer: D. 8 16
There are 2⁴ = 16 masks including the empty set (sum 0, even). With at least one odd element, exactly half the subsets have even sum: 8. Bitmask enumeration is O(2ⁿ · n), fine for n ≤ 20.
More Coding Interview Problems questions
- Problem: Find the missing number in an array containing n distinct values from 0..n. python def missing(a): x = len(a) for i, v in…
- Problem: Compute 2⁴⁰ mod (10⁹ + 7) by fast power in Java (long arithmetic). java static long power(long b, long e, long m) { long r = 1; b…
- Problem: Sum the remainders of a list of signed deltas modulo 3 in C++ and in Python. cpp int a = -7 % 3; int b = 7 % -3; int c = ((-7 %…
- Problem: Sum the prices of n = 100000 items, each 50000, in Java. java int n = 100000, price = 50000; int total = n price; long total2 = n…
- Problem: Count primes below n with the sieve of Eratosthenes. python def countprimes(n): if n < 3: return 0 isp = [True] n; isp[0] =…
- Problem: Compute nCr mod p for many queries using precomputed factorials and Fermat inverses (p prime). python M = 109 + 7 N = 20 fact =…