Given a sorted array of distinct positive integers, print all triplets that forms an arithmetic progression with an integral common difference.

An arithmetic progression is a sequence of numbers such that the difference between the consecutive terms is constant. For instance, sequence 5, 7, 9, 11, 13, 15, … is an arithmetic progression with a common difference of 2.

 
For example,

Input:  A[] = { 5, 8, 9, 11, 12, 15 }
 
Output:
5 8 11
9 12 15
 
 
Input:  A[] = { 1, 3, 5, 6, 8, 9, 15 }
 
Output:
1 3 5
1 5 9
3 6 9
1 8 15
3 9 15

Practice this problem

The idea is to consider every element as the middle element of arithmetic progression, starting from the second element and searching the other two arithmetic triplet elements. For an element A[j] to be middle of arithmetic progression, there exist two elements A[i] and A[k] such that (A[j] - A[i] = A[k] - A[j]) or (A[i] + A[k] == 2 × A[j]), where (0 <= i < j < k <= n-1).

Following is the C, Java, and Python program that demonstrates it:

C


Download  Run Code

Output:

1 3 5
1 5 9
3 6 9
1 8 15
3 9 15

Java


Download  Run Code

Output:

1 3 5
1 5 9
3 6 9
1 8 15
3 9 15

Python


Download  Run Code

Output:

(1, 3, 5)
(1, 5, 9)
(3, 6, 9)
(1, 8, 15)
(3, 9, 15)

The time complexity of the above solution is O(n2) as for every j in an input array of size n, finding i and k takes in linear time. The auxiliary space required by the program is O(1).