
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
Print all triplets in sorted array that form AP in C++
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
#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
- Related Articles
- Find all triplets in a sorted array that forms Geometric Progression in C++
- Print all triplets with given sum in C++
- Python program to print sorted number formed by merging all elements in array
- Print all permutations in sorted (lexicographic) order in C++
- Merge two sorted arrays to form a resultant sorted array in JavaScript
- Print sorted distinct elements of array in C language
- Count Triplets That Can Form Two Arrays of Equal XOR in C++
- To print all elements in sorted order from row and column wise sorted matrix in Python
- Maximum value of XOR among all triplets of an array in C++
- All unique triplets that sum up to a given value in C++
- Maximum adjacent difference in an array in its sorted form in C++
- Maximum in an array that can make another array sorted in C++
- Print all valid words that are possible using Characters of Array in C++\n
- Print k different sorted permutations of a given array in C Program.
- Count ways to form minimum product triplets in C++

Advertisements