# Count the triplets such that A[i] < B[j] < C[k] in C++

We are given with three arrays A[], B[] and C[]. The goal is to find all triplets of elements of these arrays such that A[i]<B[j]<C[k]. All three arrays have the same number of elements N. We will do this by traversing each array once and compare if A[i]<B[j] && B[j]<C[k]. If true increment count.

Let’s understand with examples.

Input

A[]={1,4,5 } B = { 0,2,3 } C = { 0,6,7 }

Output − Count of triplets − 4

Explanation

Triplets such that A[i]<B[j]<C[k]
(1,2,6) , (1,2,7) , (1,3,6) , (1,3,7). Total 4 triplets.

Input

A[]={7,8,9} B = { 4,5,6 } C = { 1,2,3 }

Output − Count of triplets: 0

Explanation

No Triplets that satisfy A[i]<B[j]<C[k]

## Approach used in the below program is as follows

• We take integer arrays A[], B[] and C[] of equal length initialized with random numbers.

• Take variable N to store their length.

• Function countTriplets(int a[],int b[],int c[], int n) takes all three arrays as input with their same length n and returns triplets that satisfy the given condition.

• Travers using three loops for each array.

• Outermost loop 0<=i<n for a[], inner 0<=j<n for b[] and innermost 0<=k<n for c[].

• Compare if a[i]<b[j] and b[j]<c[k]. If true increment count.

• At the end of all loops count will have triplets such that a[i]<b[j]<c[k].

• Return count as result.

## Example

Live Demo

#include <bits/stdc++.h>
using namespace std;
int countTriplets(int a[],int b[],int c[], int n){
int count = 0;
for (int i = 0; i < n; i++){
for (int j = 0; j < n; j++){
for (int k = 0; k < n; k++){
if(a[i]<b[j] && b[j]<c[k])
{ count++; }
}
}
}
return count;
}
int main(){
int A[]={ 1,2,3}; int B[]={ 2,3,2}; int C[]={ 4,3,1};
int N=3; //length of array
cout <<endl<< "Number of triplets : "<<countTriplets(A,B,C,N);
return 0;
}

## Output

If we run the above code it will generate the following output −

Number of triplets : 6