Introduction
Problem Statement
The problem is to get the count of unordered pair of indices such that the ratio of elements at these indices is same as the ratio of indices we are given an array of length N, we have to find the count of the unordered pairs (i, j) in the array such that ratio of elements of these indices is same as the ratio of indices (arr[i]/arr[j] = i/j). So before we look into the solution to this problem, we should first look at some examples to understand the problem better.
Sample Examples
Example 1:
Input: arr[]= {4, 1, 12, 5}
Output: 1
Explanation:
The pair is:
(1, 3) as arr[3] / arr[1] = 12 / 4 = 3
Example 2:
Input: arr[]= {7, 14, 21, 28, 2}
Output: 4
Explanation:
The pairs are:
(1, 2) as arr[2] / arr[1] = 14/7 = 2
(2, 4) as arr[4] / arr[2] = 28/14 = 2
(1, 3) as arr[3] / arr[1] = 21/7 = 3
(1, 4) as arr[4] / arr[1] = 28/7 = 4
Also see, Euclid GCD Algorithm
Brute Force Approach
This problem to find the count of unordered pair of indices such that the ratio of elements at these indices is same as the ratio of indices can be solved using two nested for loops considering each possible pair (i,j)
Steps of algorithm
- We will check for every pair of (i, j), and whichever pair follows the condition, we increase the count of the answer.
- After that, we will return the answer.
Implementation in C++
// C++ code to get the count of unordered pair of indices such that the ratio of elements at these indices is same as the ratio of indices
#include <bits/stdc++.h>
using namespace std;
int countPairs(int a[], int n)
{
// to store the count of valid pairs
int ans = 0;
for (int i = 0; i < n - 1; i++)
{
for (int j = i + 1; j < n; j++)
{
// to check if the pair is valid
if ((a[j] % a[i] == 0) && ((j + 1) % (i + 1)) == 0 && (a[j] / a[i] == (j + 1) / (i + 1)))
{
ans++;
}
}
}
// return the answer
return ans;
}
// Driver Code
int main()
{
int arr[] = {5, 10, 4, 1, 6, 8};
int n = sizeof(arr) / sizeof(arr[0]);
// Function Call
cout << countPairs(arr, n);
return 0;
}
Output:
Input: arr={5, 10, 4, 1, 6, 8}
Output: 2
Complexity Analysis
Time Complexity: O(N*N)
Since we are using two nested loops to solve the above problem, therefore, the time complexity of the approach is O(N*N).
Space Complexity: O(1)