Data Structures & AlgorithmsModerateTCS NQT · sorting

Problem: What is the sum of |ai - aj| over all pairs i < j of the sorted array [1, 4, 6]? Run the code.

Problem: What is the sum of |a_i - a_j| over all pairs i < j of the sorted array [1, 4, 6]? Run the code.
a = sorted([1, 4, 6])
print(sum(abs(a[i] - a[j]) for i in range(len(a)) for j in range(i + 1, len(a))))
What is printed?
  1. A. 8
  2. B. 12
  3. C. 10
  4. D. 6

Correct answer: C. 10

On the sorted array each a[i] is added i times and subtracted (n − 1 − i) times: 1·(−2) + 4·0 + 6·2 = 10, matching the differences 3 + 5 + 2. Summing only adjacent gaps gives 5, and counting ordered pairs would double it.

More Coding Interview Problems questions

Exams that ask this topic