Subtract invalid triplets
for ( int i = 0 ; i < n ; i ++ ) { for ( int j = i + 1 ; j < n ; j ++ ) { if ( ( 2 * j - i ) < n && s [ j ] != s [ i ] && s [ j * 2 - i ] != s [ j ] && s [ 2 * j - i ] != s [ i ] ) Total_triplet -- ; } } cout << Total_triplet ; }