Data Structures & AlgorithmsVery hardTCS CodeVita · Microsoft SDE OA

Array a = [3, 8, 2, 9, 5, 7, 6]. Count the index triples i < j < k such that the three values, sorted, are equally spaced (an arithmetic progression). Run the brute-force code.

Array a = [3, 8, 2, 9, 5, 7, 6]. Count the index triples i < j < k such that the three values, sorted, are equally spaced (an arithmetic progression). Run the brute-force code.
from itertools import combinations
a=[3,8,2,9,5,7,6]
print(sum(1 for t in combinations(a,3) if sorted(t)[1]-sorted(t)[0]==sorted(t)[2]-sorted(t)[1]))
What is printed?
  1. A. 5
  2. B. 2
  3. C. 7
  4. D. 0

Correct answer: C. 7

Sort the three values and check that the two gaps are equal. Testing the spacing in array order rather than sorted order is a different condition, counting increasing triples ignores spacing, and comparing the outer span with one gap is a misread condition.

More Coding Interview Problems questions

Exams that ask this topic