Data Structures & AlgorithmsModerateTCS NQT · hashing warm-up

Problem: How many unordered pairs of distinct elements of [1, 5, 3, 9, 7, 2] have absolute difference exactly 2? Run the code.

Problem: How many unordered pairs of distinct elements of [1, 5, 3, 9, 7, 2] have absolute difference exactly 2? Run the code.
a = [1, 5, 3, 9, 7, 2]
print(sum(1 for i in range(len(a)) for j in range(i + 1, len(a)) if abs(a[i] - a[j]) == 2))
What is printed?
  1. A. 3
  2. B. 2
  3. C. 4
  4. D. 5

Correct answer: C. 4

The pairs (1,3), (3,5), (5,7) and (7,9) have difference 2, giving 4. A hash-set lookup of x + 2 counts the same pairs in O(n).

More Coding Interview Problems questions

Exams that ask this topic