Count pairs with product of indices equal to the product of elements present at those indices
Last Updated :
29 Apr, 2021
Given an array arr[] consisting of N integers, the task is to count the number of distinct pairs of array elements having the product of indices equals the product of elements at that indices. The pairs (x, y) and (y, x) are considered as the same pairs.
Examples:
Input: arr[] = {1, 0, 3, 2, 6}
Output: 3
Explanation: All possible pairs satisfying the given criteria are:
- (0, 1): Product of indices = 1 * 0 = 0. Product of elements = 1 * 0 = 0.
- (2, 3): Product of indices = 2 * 3 = 6. Product of elements = 3 * 2 = 6.
- (3, 4): Product of indices = 3 * 4 = 12. Product of elements = 2 * 6 = 12.
Therefore, the total count of pairs is 3.
Input: arr[] = {4, -1, 2, 6, 2, 10}
Output: 2
Approach: The given problem can be solved by generating all possible distinct pairs of elements (arr[i], arr[j]) from the given array and if the product of i and j is equal to the product of array elements arr[i] and arr[j], then increment the count of such pairs. After checking for all the distinct pairs, print the total count as the result.
Below is the implementation of the above approach:
C++
#include <iostream>
using namespace std;
int CountPairs( int arr[], int n)
{
int count = 0;
for ( int i = 0; i < n - 1; i++) {
for ( int j = i + 1; j < n; j++) {
if ((i * j) == (arr[i] * arr[j]))
count++;
}
}
return count;
}
int main()
{
int arr[] = { 1, 0, 3, 2, 6 };
int N = sizeof (arr) / sizeof (arr[0]);
cout << CountPairs(arr, N);
return 0;
}
|
Java
import java.util.*;
class GFG{
static int CountPairs( int [] arr, int n)
{
int count = 0 ;
for ( int i = 0 ; i < n - 1 ; i++)
{
for ( int j = i + 1 ; j < n; j++)
{
if ((i * j) == (arr[i] * arr[j]))
count++;
}
}
return count;
}
public static void main (String[] args)
{
int [] arr = { 1 , 0 , 3 , 2 , 6 };
int N = arr.length;
System.out.println(CountPairs(arr, N));
}
}
|
Python3
def CountPairs(arr, n):
count = 0
for i in range (n - 1 ):
for j in range (i + 1 , n):
if ((i * j) = = (arr[i] * arr[j])):
count + = 1
return count
if __name__ = = "__main__" :
arr = [ 1 , 0 , 3 , 2 , 6 ]
N = len (arr)
print (CountPairs(arr, N))
|
C#
using System;
class GFG{
static int CountPairs( int [] arr, int n)
{
int count = 0;
for ( int i = 0; i < n - 1; i++)
{
for ( int j = i + 1; j < n; j++)
{
if ((i * j) == (arr[i] * arr[j]))
count++;
}
}
return count;
}
public static void Main()
{
int [] arr = { 1, 0, 3, 2, 6 };
int N = arr.Length;
Console.Write(CountPairs(arr, N));
}
}
|
Javascript
<script>
function CountPairs(arr , n) {
var count = 0;
for (i = 0; i < n - 1; i++) {
for (j = i + 1; j < n; j++) {
if ((i * j) == (arr[i] * arr[j]))
count++;
}
}
return count;
}
var arr = [ 1, 0, 3, 2, 6 ];
var N = arr.length;
document.write(CountPairs(arr, N));
</script>
|
Time Complexity: O(N2)
Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...