Data Structures & AlgorithmsHardICPC regional · counting

Problem: How many 3-element subsets of {1, 2, 3, 4, 5, 6} have a sum divisible by 3? Run the code.

Problem: How many 3-element subsets of {1, 2, 3, 4, 5, 6} have a sum divisible by 3? Run the code.
from itertools import combinations
print(sum(1 for c in combinations(range(1, 7), 3) if sum(c) % 3 == 0))
What is printed?
  1. A. 6
  2. B. 4
  3. C. 48
  4. D. 8

Correct answer: D. 8

Residues mod 3 of 1..6 are two each of 0, 1, 2; a triple sums to 0 mod 3 if it is all one residue (3 × C(2,3) = 0) or one of each (2 × 2 × 2 = 8), so 8. Assuming one third of the 20 triples gives 6, using range(1, 6) gives 4, and counting ordered triples gives 48.

More Coding Interview Problems questions

Exams that ask this topic