Data Structures & AlgorithmsVery hardICPC regional · bitmask round

Problem: Count the subsets (including the empty subset) of {1, 2, 3, 4, 5, 6} whose sum is divisible by 3.

Problem: Count the subsets (including the empty subset) of {1, 2, 3, 4, 5, 6} whose sum is divisible by 3.
a = [1, 2, 3, 4, 5, 6]
cnt = 0
for m in range(1 << len(a)):
    if sum(a[i] for i in range(len(a)) if m >> i & 1) % 3 == 0:
        cnt += 1
print(cnt)
What is printed?
  1. A. 24
  2. B. 20
  3. C. 28
  4. D. 32

Correct answer: A. 24

Group by residues mod 3: {3,6} are free (4 choices), and the residue-1/2 pieces {1,4} and {2,5} give 6 combinations that sum to 0 mod 3. Total 6 * 4 = 24.

More Coding Interview Problems questions

Exams that ask this topic