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?
  1. A. 7 16
  2. B. 8 15
  3. C. 9 16
  4. 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

Exams that ask this topic