Data Structures & AlgorithmsHardProduct Company SDE · CP practice

Problem: How many non-empty subsets of {1, 2, 3, 4, 5, 6, 7, 8} have a sum that is a multiple of 4? Run the code.

Problem: How many non-empty subsets of {1, 2, 3, 4, 5, 6, 7, 8} have a sum that is a multiple of 4? Run the code.
from itertools import combinations
a = list(range(1, 9))
print(sum(1 for r in range(1, 9) for c in combinations(a, r) if sum(c) % 4 == 0))
What is printed?
  1. A. 64
  2. B. 127
  3. C. 63
  4. D. 18

Correct answer: C. 63

Enumeration finds 63 non-empty subsets with sum ≡ 0 (mod 4). Including the empty set gives 64, counting even sums gives 127, and checking only 4-element subsets gives 18.

More Coding Interview Problems questions

Exams that ask this topic