Given a array a[] of n integers. Count the number of pairs (i, j) in the array such that a[i] * a[j] = 0.
Examples :
Input : a[] = {3, 0, 5}
Output : 2
Pairs are (3, 0) and (0,5)
Input : a[] = {1, 1, 1}
Output : 0
Naive Approach :
For each value a[i] count the number of a[j] (i > j) such that a[i]*a[j] = 0.
Implementation :
// Naive C++ program to count number of pairs
// such that their product is zero.
#include<bits/stdc++.h>
using namespace std;
// Returns the number of valid pairs
int countPairs (int arr[], int n)
{
int ans = 0; // initializing answer
// Traversing the array. For each array
// element, checking its predecessors that
// follow the condition
for (int i = 0; i<n; i++)
for (int j = i-1; j>= 0; j--)
if (arr[i]*arr[j] == 0)
ans++;
return ans;
}
// Driver function
int main()
{
int arr[] = {3, 0, 5};
int n = sizeof(arr)/sizeof(arr[0]);
cout << countPairs(arr, n);
return 0;
}
Output :
2
Efficient Approach :
To solve this problem, count the number of 0s in the array say zeroCount and non 0s in the array say nonZeroCount. Therfore the answer will be zeroCount * nonZeroCount + zeroCount * (zeroCount – 1) / 2 where the last term counts the pairs of two zeros
// C++ implementation of efficient approach
// to count valid pairs.
#include<bits/stdc++.h>
using namespace std;
// returns the number of valid pairs
int CountPairs (int arr[], int n)
{
// traversing the array, counting the
// number of 0s and non 0s
int zeroCount = 0, nonZeroCount = 0;
for (int i = 0; i<n; i++)
{
if (arr[i] == 0)
zeroCount++;
else
nonZeroCount++;
}
return zeroCount * nonZeroCount + zeroCount * (zeroCount - 1) / 2;
}
// Driver function
int main()
{
int arr[] = {3, 0, 5};
int n = sizeof(arr)/sizeof(arr[0]);
cout << CountPairs(arr, n);
return 0;
}
Output :
2