Saturday, 23 Oct 2021

# Count number of pairs (i, j) from an array such that arr[i] * j = arr[j] * i

Count number of pairs (i, j) from an array such that arr[i] * j = arr[j] * i
Given an array arr[] of size N, the task is to count the number of pairs (i, j) possible from the array such that arr[j] * i = arr[i] * j, where 1 ≤ i < j ≤ N.
Examples:

Input: arr[] = {1, 3, 5, 6, 5}Output: 2Explanation: Pair (1, 5) satisfies the condition, since arr * 5 = arr * 1.Pair (2, 4) satisfies the condition, since arr * 4 = arr * 2. Therefore, total number of pairs satisfying the given condition is 2.
Input: arr[] = {2, 1, 3}Output: 0

Naive Approach: The simplest approach to solve the problem is to generate all possible pairs from the array and check for each pair, whether the given condition satisfies or not. Increase count for the pairs for which the condition is satisfied. Finally, print the count of all such pairs. Time Complexity: O(N2)Auxiliary Space: O(1)
Efficient Approach: To optimize the above approach, the idea is based on the rearrangement of the given equation arr[i] * j = arr[j] * i to arr[i] / i = arr[j] / j. Follow the steps below to solve the problem:
Initialize a variable, say count, to store the total count of pairs satisfying the given conditions.
Initialize an Unordered Map, say mp, to count the frequency of values arr[i] / i.
Traverse the array arr[] and update the frequencies of arr[i]/i in the Map.
Print the count as the answer.
Below is the implementation of the above approach:

C++

#include
using namespace std;

void countPairs(int arr[], int N)
{

int count = 0;

unordered_map mp;

for (int i = 0; i < N; i++) {
double val = 1.0 * arr[i];
double idx = 1.0 * (i + 1);

count += mp[val / idx];

mp[val / idx]++;
}

cout