Given an array A[] of integers. Your task is to output the count of triplets such that in each triplet, there can be at most 2 same elements.
Examples:
Input: A[] = [5, 5, 2, 5]
Output: 3
Explanation: The triplets satisfying given condition are:
- 1st Triplet: (A0, A1, A2) = (5, 5, 2). As there are at most two 5 are present, therefore it’s a valid triplet.
- 2nd Triplet: (A0, A2, A3) = (5, 2, 5). As there are at most two 5 are present, therefore it’s a valid triplet.
- 3rd Triplet: (A1, A2, A3) = (5, 2, 5). As there are at most two 5 are present, therefore it’s a valid triplet.
Since there are a total of 3 triplets that is (5, 5, 2), (5, 2, 5), and (5, 2, 5), we will return 3.
Input: A[] = {2, 4, 5}
Output: 1
Explanation: There is only one triplet satisfying given condition. Which is (2, 4, 5). Since, there can be at most 2 same element, but this triplet contains all different elements. Therefore, it’s a valid triplet.Input: A[] = {4, 4, 4, 4}
Output: 0
Explanation: All possible combinations of triplets contain more than 2 same elements. Therefore, there are no valid triplets.
Approach: To solve the problem follow the below idea.
Check for all the possible combination of triplets and check manually that, if there are at most two same element the count that triplet else don’t consider it. At the end return the count of valid triplets.
Steps were taken to implement the approach:
- Create a variable let say Count to store the count of valid triplets.
-
Run 3 nested loops, create all the possible combination of triplets and check below condition:
-
If (A[i] != A[j] Or A[j] != A[k])
- Increment Count.
-
If (A[i] != A[j] Or A[j] != A[k])
- Return Count.
Below is the implement of the above approach:
#include <iostream> using namespace std;
class Geek {
public :
static int checkTriplets( int A[], int n)
{
// Variable to store count of the valid triplets
int count = 0;
// Loops for making combination of the all possible triplets
for ( int i = 0; i < n - 2; i++) {
for ( int j = i + 1; j < n - 1; j++) {
for ( int k = j + 1; k < n; k++) {
// Check if the triplet has at most
// 2 identical elements
if (A[i] != A[j] || A[j] != A[k]) {
count++;
}
}
}
}
return count;
}
}; // Main Function int main()
{ // Input A[]
int A[] = { 5, 5, 2, 5 };
int n = sizeof (A) / sizeof (A[0]);
// Create an instance of the GFG class
Geek gfg;
// Function call
cout << gfg.checkTriplets(A, n);
return 0;
} |
// C++ code to implement the approach class GFG {
// Function to return count of valid triplets
static int checkTriplets( int [] A)
{
// Variable to store length of A
int n = A.length;
// Variable to store count of valid triplets
int count = 0 ;
// Loops for making combination all possible
// triplets
for ( int i = 0 ; i < n - 2 ; i++) {
for ( int j = i + 1 ; j < n - 1 ; j++) {
for ( int k = j + 1 ; k < n; k++) {
// Check if the triplet has at most 2
// identical elements
if (A[i] != A[j] || A[j] != A[k]) {
count++;
}
}
}
}
return count;
}
// Main Function
public static void main(String[] args)
{
// Input A[]
int A[] = { 5 , 5 , 2 , 5 };
// Function call
System.out.print(checkTriplets(A));
}
} |
class GFG:
@staticmethod
def check_triplets(A):
# Variable to store length of A
n = len (A)
# Variable to store count of valid triplets
count = 0
# Loops for making combination all possible triplets
for i in range (n - 2 ):
for j in range (i + 1 , n - 1 ):
for k in range (j + 1 , n):
# Check if the triplet has at most 2 identical elements
if A[i] ! = A[j] or A[j] ! = A[k]:
count + = 1
return count
# Main Function
def main():
# Input A[]
A = [ 5 , 5 , 2 , 5 ]
# Function call
print (GFG.check_triplets(A))
# Running the main function GFG.main() |
using System;
public class GFG
{ public static int CheckTriplets( int [] A)
{
// Variable to store length of A
int n = A.Length;
// Variable to store count of valid triplets
int count = 0;
// Loops for making combinations of all possible triplets
for ( int i = 0; i < n - 2; i++)
{
for ( int j = i + 1; j < n - 1; j++)
{
for ( int k = j + 1; k < n; k++)
{
// Check if the triplet has at most 2 identical elements
if (A[i] != A[j] || A[j] != A[k])
{
count++;
}
}
}
}
return count;
}
// Main Function
public static void Main( string [] args)
{
// Input A[]
int [] A = { 5, 5, 2, 5 };
// Function call
Console.WriteLine(CheckTriplets(A));
}
} |
class Geek { static checkTriplets(A, n) {
// Variable to store count of
// the valid triplets
let count = 0;
// Loops for making combination of
// the all possible triplets
for (let i = 0; i < n - 2; i++) {
for (let j = i + 1; j < n - 1; j++) {
for (let k = j + 1; k < n; k++) {
if (A[i] !== A[j] || A[j] !== A[k]) {
count++;
}
}
}
}
return count;
}
} // Input A[] const A = [5, 5, 2, 5]; const n = A.length; // Create an instance of the Geek class // const gfg = new Geek(); // Function call console.log(Geek.checkTriplets(A, n)); |
3
Time Complexity: O(N3)
Auxiliary space: O(1)
Optimal Approach: We can solve this problem optimally using below idea:
The problem can also be solved using the Combinatorics. Calculate and store frequency of each element into frequency array let say Freq[]. Then count of valid triplets = (Total possible triplets – invalid triplets).
- Where, invalid triplets are the triplets with all 3 same elements.
Steps were taken to solve the problem:
- Create a frequency array let say F[].
- Run a loop to iterate A[] and initialize frequency in F[] of each element.
- Create a variable let say Total_triplets and initialize it with (N*(N-1)*(N-2))/6
-
Run a loop to iterate over F[] and follow below mentioned steps under the scope of loop:
-
If (frequency of current element == 2)
- Continue loop.
- Invalid triplets (with respect to current element) = (Fi*(Fi – 1)*(Fi – 2))/6
- Total_triplets -= Invalid triplets
-
If (frequency of current element == 2)
- return Invalid triplets.
Below is the implement of the above approach:
// C++ code to implement optimal approach #include <iostream> using namespace std;
// Function to return valid triplets int countTriplets( int A[], int N) {
// array to store distinct elements
int F[1001] = {0};
// getting the frequency of each distinct number
for ( int i = 0; i < N; ++i) {
F[A[i]]++;
}
// Total possible triplets
int totalTriplets = N * (N - 1) * (N - 2) / 6;
for ( int freq : F) {
// avoiding case where all numbers in triplet
// are the same.
if (freq < 2) {
continue ;
}
// handling case where all 3 elements are the same
// (invalid triplets), using the combination formula
// again
int allSame = freq * (freq - 1) * (freq - 2) / 6;
// Subtracting invalid triplets with respect to
// the current element
totalTriplets = totalTriplets - allSame;
}
// returning the count of valid triplets
return totalTriplets;
} // Main Function int main() {
// Input A
int A[] = { 5, 5, 2, 5 };
int N = sizeof (A) / sizeof (A[0]);
// Printing count of triplets by calling
// countTriplets() function
cout << countTriplets(A, N);
return 0;
} |
// CPP code to implement optimal approach class GFG {
// Function to return valid triplets
static int CountTriplets( int [] A)
{
int N = A.length;
// array to store distinct elements
int [] F = new int [ 1001 ];
// getting the frequency of each distinct number
for ( int element : A) {
F[element]++;
}
// Total possible triplets
int total_triplets = N * (N - 1 ) * (N - 2 ) / 6 ;
for ( int freq : F) {
// avoiding case where all numbers in triplet
// are same.
if (freq < 2 ) {
continue ;
}
// handling case where all 3 elements are same
// (invalid triplets), using combination formula
// again
int allSame
= freq * (freq - 1 ) * (freq - 2 ) / 6 ;
// Subtracting invalid triplets with respect to
// current element
total_triplets = total_triplets - (allSame);
}
// returning the count of valid triplets
return total_triplets;
}
// Main Function
public static void main(String[] args)
{
// Input A
int A[] = { 5 , 5 , 2 , 5 };
// Printing count of triplets by calling
// CountTriplets() function
System.out.print(CountTriplets(A));
}
} |
def count_triplets(arr):
# Array to store distinct elements
F = [ 0 ] * 1001
# Getting the frequency of each distinct number
for element in arr:
F[element] + = 1
# Total possible triplets
total_triplets = len (arr) * ( len (arr) - 1 ) * ( len (arr) - 2 ) / / 6
# Loop over the frequency array
for freq in F:
# Avoiding the case where all numbers in triplet are the same
if freq < 2 :
continue
# Handling the case where all 3 elements are the same (invalid triplets)
all_same = freq * (freq - 1 ) * (freq - 2 ) / / 6
# Subtracting invalid triplets with respect to the current element
total_triplets - = all_same
# Returning the count of valid triplets
return total_triplets
# Main Function if __name__ = = "__main__" :
# Input array A
A = [ 5 , 5 , 2 , 5 ]
# Printing count of triplets by calling count_triplets() function
print (count_triplets(A))
|
using System;
class Program
{ // Function to return valid triplets
static int CountTriplets( int [] A, int N)
{
// array to store distinct elements
int [] F = new int [1001];
// getting the frequency of each distinct number
foreach ( int num in A)
{
F[num]++;
}
// Total possible triplets
int totalTriplets = N * (N - 1) * (N - 2) / 6;
foreach ( int freq in F)
{
// avoiding case where all numbers in triplet
// are the same.
if (freq < 2)
{
continue ;
}
// handling case where all 3 elements are the same
// (invalid triplets), using the combination formula
// again
int allSame = freq * (freq - 1) * (freq - 2) / 6;
// Subtracting invalid triplets with respect to
// the current element
totalTriplets = totalTriplets - allSame;
}
// returning the count of valid triplets
return totalTriplets;
}
// Driver code
static void Main( string [] args)
{
// Input A
int [] A = { 5, 5, 2, 5 };
int N = A.Length;
// Printing count of triplets by calling
// CountTriplets() function
Console.WriteLine(CountTriplets(A, N));
}
} |
// Function to return valid triplets function countTriplets(A) {
// array to store distinct elements
let F = new Array(1001).fill(0);
// getting the frequency of each distinct number
for (let i = 0; i < A.length; ++i) {
F[A[i]]++;
}
// Total possible triplets
let totalTriplets = (A.length * (A.length - 1) * (A.length - 2)) / 6;
for (let freq of F) {
// avoiding case where all numbers in triplet
// are the same.
if (freq < 2) {
continue ;
}
// handling case where all 3 elements are the same
// (invalid triplets), using the combination formula
// again
let allSame = (freq * (freq - 1) * (freq - 2)) / 6;
// Subtracting invalid triplets with respect to
// the current element
totalTriplets -= allSame;
}
// returning the count of valid triplets
return totalTriplets;
} // Main Function function main() {
// Input A
let A = [5, 5, 2, 5];
// Printing count of triplets by calling
// countTriplets() function
console.log(countTriplets(A));
} // Call the main function main(); //This code is contributed by Adarsh. |
3
Time Complexity: O(N)
Auxiliary Space: O(1), As frequency array Freq[] of size 1000 is used.