Data Structures & AlgorithmsHardProduct Company SDE · CP practice

Problem: How many subsets of {1, 2, ..., 12} have an odd sum? Run the code.

Problem: How many subsets of {1, 2, ..., 12} have an odd sum? Run the code.
print(sum(1 for m in range(1 << 12) if sum(i + 1 for i in range(12) if m >> i & 1) % 2 == 1))
What is printed?
  1. A. 4096
  2. B. 32
  3. C. 2048
  4. D. 64

Correct answer: C. 2048

The sum is odd iff an odd number of the 6 odd elements is chosen: 2⁵ ways for the odds times 2⁶ for the evens = 2048, half of all subsets. 4096 counts every subset, 32 forgets the evens, and 64 counts only the even elements' choices.

More Coding Interview Problems questions

Exams that ask this topic