Data Structures & AlgorithmsModerateProduct Company SDE · CP practice

Problem: How many pairs (i < j) of [5, 6, 7, 9, 8] satisfy |ai - aj| = 1? Run the code.

Problem: How many pairs (i < j) of [5, 6, 7, 9, 8] satisfy |a_i - a_j| = 1? Run the code.
a = [5, 6, 7, 9, 8]
print(sum(1 for i in range(len(a)) for j in range(i + 1, len(a)) if abs(a[i] - a[j]) == 1))
What is printed?
  1. A. 3
  2. B. 5
  3. C. 4
  4. D. 2

Correct answer: C. 4

The adjacent-value pairs are (5,6), (6,7), (7,8) and (9,8), giving 4.

More Coding Interview Problems questions

Exams that ask this topic