Data Structures & AlgorithmsHardCodeforces Div2 C/D · Amazon SDE OA

Count the unordered pairs (i < j) of the array a = [1, 2, ..., 14] whose sum is divisible by 3. Run the code.

Count the unordered pairs (i < j) of the array a = [1, 2, ..., 14] whose sum is divisible by 3. Run the code.
a=list(range(1,15))
c=[0,0,0]
for x in a: c[x%3]+=1
print(c[0]*(c[0]-1)//2+c[1]*c[2])
What is printed?
  1. A. 66
  2. B. 35
  3. C. 31
  4. D. 26

Correct answer: C. 31

Pairs sum to a multiple of 3 when residues are (0,0) or (1,2), so the count is C(c0,2)+c1·c2 = 6+25. Including i = j counts a pair that is not allowed, squaring instead of choosing pairs counts ordered pairs, and pairing within each residue class ignores the cross pairs.

More Coding Interview Problems questions

Exams that ask this topic