Data Structures & AlgorithmsHardProduct Company SDE · CP practice

Problem: How many pairs (i < j) of [1, 4, 9, 16, 25] have a[j] - a[i] divisible by 3? Run the code.

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

Correct answer: C. 6

Residues mod 3 are 1, 1, 0, 1, 1, so the four 1s give C(4,2) = 6 pairs. Ordered pairs give 12, adjacent pairs only give 2, and testing the sum instead of the difference gives 0.

More Coding Interview Problems questions

Exams that ask this topic