Subtract invalid triplets
for ( int i = 0 ; i < n ; i ++ ) { for ( int j = i + 1 ; j < n ; j ++ ) { if ( ( 2 * j - i ) < n && s . charAt ( j ) != s . charAt ( i ) && s . charAt ( j * 2 - i ) != s . charAt ( j ) && s . charAt ( 2 * j - i ) != s . charAt ( i ) ) Total_triplet -- ; } } System . out . println ( Total_triplet ) ; }