Data Structures & AlgorithmsHardTCS NQT Digital · counting

Problem: How many pairs (i < j) of a = [1, 2, 3, 4, 5, 6, 7] have a[i] + a[j] divisible by 4?

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

Correct answer: A. 5

The qualifying pairs are (1,3), (1,7), (2,6), (3,5) and (5,7), for a total of 5. Counting by residue classes mod 4 gives the same result in O(n).

More Coding Interview Problems questions

Exams that ask this topic