Count non | C ++ program to implement the above approach ; Function to find the total count of triplets ( i , j , k ) such that i < j < k and ( j - i ) != ( k - j ) ; Stores indices of 0 s ; Stores indices of 1 s ; Stores indices of 2 s ; Traverse the array ; If current array element is 0 ; If current array element is 1 ; If current array element is 2 ; Total count of triplets ; Traverse the array zero_i [ ] ; Traverse the array one_i [ ] ; Stores index of 0 s ; Stores index of 1 s ; Stores third element of triplets that does not satisfy the condition ; If r present in the map ; Update r ; If r present in the map ; Update r ; If r present in the map and equidistant ; Print the obtained count ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countTriplets ( int * arr , int N ) { vector < int > zero_i ; vector < int > one_i ; unordered_map < int , int > mp ; for ( int i = 0 ; i < N ; i ++ ) { if ( arr [ i ] == 0 ) zero_i . push_back ( i + 1 ) ; else if ( arr [ i ] == 1 ) one_i . push_back ( i + 1 ) ; else mp [ i + 1 ] = 1 ; } int total = zero_i . size ( ) * one_i . size ( ) * mp . size ( ) ; for ( int i = 0 ; i < zero_i . size ( ) ; i ++ ) { for ( int j = 0 ; j < one_i . size ( ) ; j ++ ) { int p = zero_i [ i ] ; int q = one_i [ j ] ; int r = 2 * p - q ; if ( mp [ r ] > 0 ) total -- ; r = 2 * q - p ; if ( mp [ r ] > 0 ) total -- ; r = ( p + q ) / 2 ; if ( mp [ r ] > 0 && abs ( r - p ) == abs ( r - q ) ) total -- ; } } cout << total ; } int main ( ) { int arr [ ] = { 0 , 1 , 2 , 1 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; countTriplets ( arr , N ) ; return 0 ; }