Print all triplets in sorted array that form AP in C++

C++Server Side ProgrammingProgramming

In this problem, we are given a sorted array of numbers and we need to find the triplets with are in the form of arithmetic progression.

An arithmetic progression is a series of numbers in which the difference between consecutive terms is the same.

Let’s take an example to understand the problem better −

Input :
array = {2 , 5 , 7, 8 , 9 , 10}
Output :
2 5 8
5 7 9
7 8 9
8 9 10

To solve this problem, a simple solution would be running three loops and checking all triplets if they are in AP. but this method has a time complexity of the order n3.

A better solution is using hashing. In this method, we will start from the second element of the array and treat every element as a middle element of the AP and check if it forms the AP or not.

Example

 Live Demo

#include <iostream>
using namespace std;
void TripletsAP(int arr[], int n){
   for (int i = 1; i < n - 1; i++){
      for (int j = i - 1, k = i + 1; j >= 0 && k < n;){
         if (arr[j] + arr[k] == 2 * arr[i]){
            cout<<arr[j]<<"\t"<<arr[i]<<"\t"<< arr[k] << endl;
            k++;
            j--;
         }
         else if (arr[j] + arr[k] < 2 * arr[i])
            k++;
         else
            j--;
      }
   }
}
int main(){
   int arr[] = {2 , 5 , 7, 8 , 9 , 10};
   int n = sizeof(arr) / sizeof(arr[0]);
   cout<<"The triplets that are in AP are : \n";
   TripletsAP(arr, n);
   return 0;
}

Output

The triplets that are in AP are −

2 5 8
5 7 9
7 8 9
8 9 10
raja
Published on 17-Jan-2020 09:39:52
Advertisements