Count triplets having product 0 from a given array

Given an array arr[] of size N, the task is to count the number of triplets (arr[i], arr[j], arr[k]) such that arr[i] * arr[j] = arr[j] * arr[k] = 0 (i < j < k).
 Examples:

Input: arr[] = {0, 8, 12, 0}
Output: 2
Explanation:
Triplets satisfying the given conditions are (0, 8, 0) and (0, 12, 0). Therefore, the required output is 2.

Input: arr[] = {1, 0, 2, 3}
Output: 2

 

Naive Approach: The simplest approach to solve this problem is to generate all possible triplets from the given array and print the count of triplets that satisfy the given conditions.

Time Complexity: O(N3)
Auxiliary Space: O(1)

Efficient Approach: To optimize the above approach, the idea is to store the count of 0s on the left side and right side of each array element using the Prefix Sum technique. Traverse the array and count the number of triplets that satisfy the given condition by considering the current element of the array as the value of arr[j]. Finally, print the count of triplets that satisfy the given condition. Follow the steps below to solve the problem:



  • Initialize an array, say prefixZero[], to store for every index, the count of 0s present in the preceding indices.
  • Initialize a variable tripletCnt to store the count of triplets that satisfy the given conditions.
  • Traverse the array and check if arr[i] equals to 0 or not. If found to be true, then increment the value of cntTriplet by i * (N – i -1).
  • Otherwise, increment the value of tripletCnt by prefixZero[i] * (prefixZero[N – 1] – prefixZero[i]).
  • Finally, print the value of tripletCnt.

Below is the implementation of the above approach:

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program to implement
// the above approach
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to get the count
// of triples that satisfy
// the given condition
int cntTriplet(int arr[], int N)
{
 
    // preZero[i] stores count
    // of 0 up to index i
    int preZero[N] = { 0 };
 
    // Traverse the array and
    // Count 0s up to index i
    for (int i = 0; i < N; i++) {
        if (arr[i] == 0) {
            preZero[i]
                = preZero[max(i - 1, 0)] + 1;
        }
        else {
            preZero[i]
                = preZero[max(i - 1, 0)];
        }
    }
 
    // Stores count of triplet that
    // satisfy the given conditions
    int tripletCount = 0;
 
    // Traverse the given array
    for (int i = 0; i < N; i++) {
        if (arr[i] == 0) {
 
            // Stores count of elements
            // on  the left side of arr[i]
            int X = i;
 
            // Stores count of elements
            // on  the right side of arr[i]
            int Y = N - i - 1;
 
            tripletCount += X * Y;
        }
 
        else {
 
            // Stores count of 0s on
            // the left side of arr[i]
            int X = preZero[i];
 
            // Stores count of 0s on
            // the right side of arr[i]
            int Y = preZero[N - 1]
                    - preZero[i];
 
            tripletCount += X * Y;
        }
    }
 
    return tripletCount;
}
 
// Driver Code
int main()
{
    int arr[] = { 1, 0, 2, 3 };
    int N = sizeof(arr) / sizeof(arr[0]);
    cout << cntTriplet(arr, N);
 
    return 0;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to implement
// the above approach
import java.util.*;
class GFG{
 
// Function to get the count
// of triples that satisfy
// the given condition
static int cntTriplet(int arr[],
                      int N)
{
  // preZero[i] stores count
  // of 0 up to index i
  int []preZero = new int[N];
 
  // Traverse the array and
  // Count 0s up to index i
  for (int i = 0; i < N; i++)
  {
    if (arr[i] == 0)
    {
      preZero[i] = preZero[Math.max(i - 1,
                                    0)] + 1;
    }
    else
    {
      preZero[i] = preZero[Math.max(i - 1, 0)];
    }
  }
 
  // Stores count of triplet that
  // satisfy the given conditions
  int tripletCount = 0;
 
  // Traverse the given array
  for (int i = 0; i < N; i++)
  {
    if (arr[i] == 0)
    {
      // Stores count of elements
      // on  the left side of arr[i]
      int X = i;
 
      // Stores count of elements
      // on  the right side of arr[i]
      int Y = N - i - 1;
 
      tripletCount += X * Y;
    }
    else
    {
      // Stores count of 0s on
      // the left side of arr[i]
      int X = preZero[i];
 
      // Stores count of 0s on
      // the right side of arr[i]
      int Y = preZero[N - 1] -
              preZero[i];
 
      tripletCount += X * Y;
    }
  }
 
  return tripletCount;
}
 
// Driver Code
public static void main(String[] args)
{
  int arr[] = {1, 0, 2, 3};
  int N = arr.length;
  System.out.print(cntTriplet(arr, N));
}
}
 
// This code contributed by gauravrajput1

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 program to implement
# the above appraoch
 
# Function to get the count
# of triples that satisfy
# the given condition
def cntTriplet(arr, N):
 
    # preZero[i] stores count
    # of 0 up to index i
    preZero = [0] * N
 
    # Traverse the array and
    # Count 0s up to index i
    for i in range(N):
        if (arr[i] == 0):
            preZero[i] = preZero[
            max(i - 1, 0)] + 1
        else:
            preZero[i] = preZero[
            max(i - 1, 0)]
 
    # Stores count of triplet that
    # satisfy the given conditions
    tripletCount = 0
 
    # Traverse the given array
    for i in range(N):
        if (arr[i] == 0):
 
            # Stores count of elements
            # on  the left side of arr[i]
            X = i
 
            # Stores count of elements
            # on  the right side of arr[i]
            Y = N - i - 1
 
            tripletCount += X * Y
 
        else:
             
            # Stores count of 0s on
            # the left side of arr[i]
            X = preZero[i]
 
            # Stores count of 0s on
            # the right side of arr[i]
            Y = preZero[N - 1] - preZero[i]
 
            tripletCount += X * Y
 
    return tripletCount
 
# Driver code
if __name__ == '__main__':
 
    arr = [ 1, 0, 2, 3 ]
    N = len(arr)
     
    print(cntTriplet(arr, N))
 
# This code is contributed by Shivam Singh

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program to implement
// the above approach
using System;
class GFG{
 
// Function to get the count
// of triples that satisfy
// the given condition
static int cntTriplet(int[] arr,
                      int N)
{
  // preZero[i] stores count
  // of 0 up to index i
  int[] preZero = new int[N];
 
  // Traverse the array and
  // Count 0s up to index i
  for (int i = 0; i < N; i++)
  {
    if (arr[i] == 0)
    {
      preZero[i] = preZero[Math.Max(i - 1,
                                    0)] + 1;
    }
    else
    {
      preZero[i] = preZero[Math.Max(i - 1, 0)];
    }
  }
 
  // Stores count of triplet that
  // satisfy the given conditions
  int tripletCount = 0;
 
  // Traverse the given array
  for (int i = 0; i < N; i++)
  {
    if (arr[i] == 0)
    {
      // Stores count of elements
      // on  the left side of arr[i]
      int X = i;
 
      // Stores count of elements
      // on  the right side of arr[i]
      int Y = N - i - 1;
 
      tripletCount += X * Y;
    }
    else
    {
      // Stores count of 0s on
      // the left side of arr[i]
      int X = preZero[i];
 
      // Stores count of 0s on
      // the right side of arr[i]
      int Y = preZero[N - 1] -
              preZero[i];
 
      tripletCount += X * Y;
    }
  }
 
  return tripletCount;
}
 
// Driver Code
public static void Main(String[] args)
{
  int[] arr = {1, 0, 2, 3};
  int N = arr.Length;
  Console.Write(cntTriplet(arr, N));
}
}
 
// This code is contributed by Chitranayal

chevron_right


Output: 

2









 

Time Complexity: O(N)
Auxiliary Space: O(N)

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.