Data Structures & AlgorithmsVery hardProduct Company SDE · CP practice

Problem: What is the number of subsets of {1, 2, ..., 8} whose elements sum to a multiple of 8? Run the code.

Problem: What is the number of subsets of {1, 2, ..., 8} whose elements sum to a multiple of 8? Run the code.
print(sum(1 for m in range(1 << 8) if sum(i + 1 for i in range(8) if m >> i & 1) % 8 == 0))
What is printed?
  1. A. 31
  2. B. 32
  3. C. 6
  4. D. 256

Correct answer: B. 32

All 256 subsets including the empty one are tested, and 32 have sum ≡ 0 (mod 8). Leaving out the empty set gives 31, requiring sum exactly 8 gives 6, and 256 counts every subset.

More Coding Interview Problems questions

Exams that ask this topic