Skip to content

Commit a589f14

Browse files
authored
Merge pull request #106 from Assassin-compiler/main
Create triplets.cpp
2 parents bfe9e75 + 83bed70 commit a589f14

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed

triplets.cpp

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
#include <bits/stdc++.h>
2+
using namespace std;
3+
4+
// Function to print all triplets in
5+
// given sorted array that forms AP
6+
void printAllAPTriplets(int arr[], int n)
7+
{
8+
unordered_set<int> s;
9+
for (int i = 0; i < n - 1; i++)
10+
{
11+
for (int j = i + 1; j < n; j++)
12+
{
13+
// Use hash to find if there is
14+
// a previous element with difference
15+
// equal to arr[j] - arr[i]
16+
int diff = arr[j] - arr[i];
17+
if (s.find(arr[i] - diff) != s.end())
18+
cout << arr[i] - diff << " " << arr[i]
19+
<< " " << arr[j] << endl;
20+
}
21+
s.insert(arr[i]);
22+
}
23+
}
24+
25+
// Driver code
26+
int main()
27+
{
28+
int arr[] = { 2, 6, 9, 12, 17,
29+
22, 31, 32, 35, 42 };
30+
int n = sizeof(arr) / sizeof(arr[0]);
31+
printAllAPTriplets(arr, n);
32+
return 0;
33+
}

0 commit comments

Comments
 (0)