Data Structures & AlgorithmsModerateTCS NQT Digital · counting

Problem: How many unordered pairs of indices (i < j) of [5, 5, 5, 5] have a sum of 10? Run the code.

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

Correct answer: A. 6

Any two of the four equal values sum to 10, so the count is C(4,2) = 6. Checking only adjacent pairs gives 3, starting j at i also pairs each element with itself (10), and counting ordered pairs gives 12.

More Coding Interview Problems questions

Exams that ask this topic