Data Structures & AlgorithmsModerateTCS NQT · number theory

Problem: How many pairs (i < j) of a = [1, 2, 4, 5, 7, 8] have a[i] - a[j] divisible by 3? Run the code.

Problem: How many pairs (i < j) of a = [1, 2, 4, 5, 7, 8] have a[i] - a[j] divisible by 3? Run the code.
a = [1, 2, 4, 5, 7, 8]
print(sum(1 for i in range(len(a)) for j in range(i + 1, len(a)) if (a[i] - a[j]) % 3 == 0))
What is printed?
  1. A. 5
  2. B. 12
  3. C. 6
  4. D. 9

Correct answer: C. 6

Equal residues mod 3 form the groups {1, 4, 7} and {2, 5, 8}, each giving C(3,2) = 3 pairs, for 6. Starting j at i also counts the 6 self-pairs (12), counting the non-divisible pairs gives 9, and assuming one third of the 15 pairs gives 5.

More Coding Interview Problems questions

Exams that ask this topic