Data Structures & AlgorithmsModerateTCS NQT · two-pointer warm-up

Problem: How many pairs (i < j) of [1, 3, 5, 7, 9] have a[i] + a[j] >= 10? Run the code.

Problem: How many pairs (i < j) of [1, 3, 5, 7, 9] have a[i] + a[j] >= 10? Run the code.
a = [1, 3, 5, 7, 9]
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. 4
  3. C. 12
  4. D. 9

Correct answer: A. 6

The pairs with sum ≥ 10 are (1,9), (3,7), (3,9), (5,7), (5,9) and (7,9): 6. Using > instead of ≥ drops the two sums of exactly 10 (4), counting ordered pairs gives 12, and starting j at i adds the self-pairs 5+5, 7+7, 9+9 (9).

More Coding Interview Problems questions

Exams that ask this topic