Count all distinct pairs with product equal to K
Given an integer array arr[] of size N and a positive integer K, the task is to count all the distinct pairs in the array with product equal to K.
Examples:
Input: arr[] = {1, 5, 3, 4, 2}, K = 3
Output: 1
Explanation:
There is only one pair (1, 3) with product = K = 3.
Input: arr[] = {1, 2, 16, 4, 4}, K = 16
Output: 2
Explanation:
There are two pairs (1, 16) and (4, 4) with product = K = 16.
Input: arr[] = {2, 3, 5, 6, 4}, K = 9
Output: 0
Explanation:
There are no such pairs with product as 9.
Efficient Approach: The idea is to use hashing.
- Traverse Array from 0 to n-1
- For every element i check
- it is not seen.
- it is not 0.
- k is divisible by element.
- k/arr[i] present in set .
- If 2nd is true increment count and add arr[i] and k/arr[i] in seen.
- add arr[i] in set ust.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int countPairsWithProductK( int arr[], int n, int k)
{
unordered_set< int > ust;
unordered_set< int > seen;
int count = 0;
for ( int i = 0; i < n; i++) {
if (seen.find(arr[i]) == seen.end() && arr[i] != 0
&& k % arr[i] == 0
&& ust.find(k / arr[i]) != ust.end()) {
count++;
seen.insert(arr[i]);
seen.insert(k / arr[i]);
}
ust.insert(arr[i]);
}
return count;
}
int main()
{
int arr[] = { 1, 5, 3, 4, 2 };
int N = sizeof (arr) / sizeof (arr[0]);
int K = 3;
cout << countPairsWithProductK(arr, N, K);
return 0;
}
|
Java
class GFG
{
static int MAX = 100000 ;
static int countPairsWithProductK( int arr[], int n, int k)
{
int count = 0 ;
int i;
boolean hashmap[] = new boolean [MAX];
for (i = 0 ; i < n; i++)
hashmap[arr[i]] = true ;
for (i = 0 ; i < n; i++) {
int x = arr[i];
double index = 1.0 * k / arr[i];
if (index >= 0
&& ((index - ( int )(index)) == 0 )
&& hashmap[k / x])
count++;
hashmap[x] = false ;
}
return count;
}
public static void main(String []args)
{
int arr[] = { 1 , 5 , 3 , 4 , 2 };
int N = arr.length;
int K = 3 ;
System.out.print(countPairsWithProductK(arr, N, K));
}
}
|
Python3
MAX = 100000 ;
def countPairsWithProductK(arr, n, k) :
count = 0 ;
hashmap = [ False ] * MAX ;
for i in range (n) :
hashmap[arr[i]] = True ;
for i in range (n) :
x = arr[i];
index = 1.0 * k / arr[i];
if (index > = 0
and ((index - int (index)) = = 0 )
and hashmap[k / / x]) :
count + = 1 ;
hashmap[x] = False ;
return count;
if __name__ = = "__main__" :
arr = [ 1 , 5 , 3 , 4 , 2 ];
N = len (arr);
K = 3 ;
print (countPairsWithProductK(arr, N, K));
|
C#
using System;
class GFG
{
static int MAX = 100000;
static int countPairsWithProductK( int []arr, int n, int k)
{
int count = 0;
int i;
bool []hashmap = new bool [MAX];
for (i = 0; i < n; i++)
hashmap[arr[i]] = true ;
for (i = 0; i < n; i++) {
int x = arr[i];
double index = 1.0 * k / arr[i];
if (index >= 0
&& ((index - ( int )(index)) == 0)
&& hashmap[k / x])
count++;
hashmap[x] = false ;
}
return count;
}
public static void Main(String []args)
{
int []arr = { 1, 5, 3, 4, 2 };
int N = arr.Length;
int K = 3;
Console.Write(countPairsWithProductK(arr, N, K));
}
}
|
Javascript
<script>
let MAX = 100000;
function countPairsWithProductK(arr,n,k)
{
let count = 0;
let i;
let hashmap = new Array(MAX);
for (i = 0; i < n; i++)
hashmap[arr[i]] = true ;
for (i = 0; i < n; i++) {
let x = arr[i];
let index = 1.0 * k / arr[i];
if (index >= 0
&& ((index - Math.floor(index)) == 0)
&& hashmap[k / x])
count++;
hashmap[x] = false ;
}
return count;
}
let arr=[1, 5, 3, 4, 2];
let N = arr.length;
let K = 3;
document.write(countPairsWithProductK(arr, N, K));
</script>
|
Time Complexity: O(N)
Auxiliary Space: O(MAX), since MAX space has been taken.
Approach 2: Sorting the array and using two pointers to find pairs whose product is equal to K..
- In the countPairs() function, the arr array is sorted in ascending order using the sort() function from the algorithm library.
- Two integer variables, count and left, are initialized to 0, and right is initialized to n-1.
- A while loop is used to compare elements from the left and right ends of the array. The loop continues as long as left is less than right.
- If the product of the values at the left and right indexes is equal to k, then the count of pairs is incremented by 1. The left and right indexes are also incremented and decremented, respectively.
- If the value at arr[left] multiplied by arr[right] is less than k, then left is incremented.
- If the value at arr[left] multiplied by arr[right] is greater than k, then right is decremented.
- Two nested while loops are used to skip over duplicates in the array. These loops continue as long as there are duplicates at the left and right indexes.
- After the while loop completes, the count of pairs is returned.
C++
#include <iostream>
#include <algorithm>
using namespace std;
int countPairs( int arr[], int n, int k)
{
sort(arr, arr + n);
int count = 0;
int left = 0, right = n - 1;
while (left < right)
{
if (arr[left] * arr[right] == k)
{
count++;
left++;
right--;
while (left < right && arr[left] == arr[left - 1])
{
left++;
}
while (left < right && arr[right] == arr[right + 1])
{
right--;
}
}
else if (arr[left] * arr[right] < k)
{
left++;
}
else
{
right--;
}
}
return count;
}
int main()
{
int arr[] = { 1, 5, 3, 4, 2 };
int n = sizeof (arr) / sizeof (arr[0]);
int k = 3;
int pairs = countPairs(arr, n, k);
cout << pairs << endl;
return 0;
}
|
Java
import java.util.Arrays;
public class CountPairs {
public static int countPairs( int [] arr, int n, int k)
{
Arrays.sort(arr);
int count = 0 ;
int left = 0 , right = n - 1 ;
while (left < right) {
if (arr[left] * arr[right] == k) {
count++;
left++;
right--;
while (left < right
&& arr[left] == arr[left - 1 ]) {
left++;
}
while (left < right
&& arr[right] == arr[right + 1 ]) {
right--;
}
}
else if (arr[left] * arr[right] < k) {
left++;
}
else {
right--;
}
}
return count;
}
public static void main(String[] args)
{
int [] arr = { 1 , 5 , 3 , 4 , 2 };
int n = arr.length;
int k = 3 ;
int pairs = countPairs(arr, n, k);
System.out.println(pairs);
}
}
|
Python3
def countPairs(arr, n, k):
arr.sort()
count = 0
left = 0
right = n - 1
while left < right:
if arr[left] * arr[right] = = k:
count + = 1
left + = 1
right - = 1
while left < right and arr[left] = = arr[left - 1 ]:
left + = 1
while left < right and arr[right] = = arr[right + 1 ]:
right - = 1
elif arr[left] * arr[right] < k:
left + = 1
else :
right - = 1
return count
arr = [ 1 , 5 , 3 , 4 , 2 ]
n = len (arr)
k = 3
pairs = countPairs(arr, n, k)
print (pairs)
|
C#
using System;
class Program {
static int CountPairs( int [] arr, int n, int k)
{
Array.Sort(arr);
int count = 0;
int left = 0, right = n - 1;
while (left < right) {
if (arr[left] * arr[right] == k) {
count++;
left++;
right--;
while (left < right
&& arr[left] == arr[left - 1]) {
left++;
}
while (left < right
&& arr[right] == arr[right + 1]) {
right--;
}
}
else if (arr[left] * arr[right] < k) {
left++;
}
else {
right--;
}
}
return count;
}
static void Main( string [] args)
{
int [] arr = { 1, 5, 3, 4, 2 };
int n = arr.Length;
int k = 3;
int pairs = CountPairs(arr, n, k);
Console.WriteLine(pairs);
}
}
|
Javascript
function countPairs(arr, n, k) {
arr.sort((a, b) => a - b);
let count = 0;
let left = 0;
let right = n - 1;
while (left < right) {
if (arr[left] * arr[right] === k) {
count++;
left++;
right--;
while (left < right && arr[left] === arr[left - 1]) {
left++;
}
while (left < right && arr[right] === arr[right + 1]) {
right--;
}
}
else if (arr[left] * arr[right] < k) {
left++;
}
else {
right--;
}
}
return count;
}
const arr = [1, 5, 3, 4, 2];
const n = arr.length;
const k = 3;
const pairs = countPairs(arr, n, k);
console.log(pairs);
|
Time Complexity: O(NlogN)
Auxiliary Space: O(1)
Approach 3(using Binary Search)
The idea is to use binary search
Algorithm
- Sort the given array arr in non-decreasing order.
- Initialize a variable count to 0.
- Iterate through the array arr and for each element arr[i], do the following:
- If K % arr[i] == 0, then do a binary search for K/arr[i] in the remaining subarray to the right of arr[i].
- If K/arr[i] is found in the subarray, increment count.
- Return count.
C++
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
int count_pairs(vector< int > arr, int K) {
int count = 0;
sort(arr.begin(), arr.end());
for ( int i = 0; i < arr.size(); i++) {
if (K % arr[i] == 0) {
int left = i + 1, right = arr.size() - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (arr[mid] == K / arr[i]) {
count++;
break ;
}
else if (arr[mid] < K / arr[i]) {
left = mid + 1;
}
else {
right = mid - 1;
}
}
}
}
return count;
}
int main() {
vector< int > arr = {1, 5, 3, 4, 2};
int K = 3;
int count = count_pairs(arr, K);
cout << "Number of distinct pairs with product " << K << " is " << count << endl;
arr = {1, 2, 16, 4, 4};
K = 16;
count = count_pairs(arr, K);
cout << "Number of distinct pairs with product " << K << " is " << count << endl;
arr = {2, 3, 5, 6, 4};
K = 9;
count = count_pairs(arr, K);
cout << "Number of distinct pairs with product " << K << " is " << count << endl;
return 0;
}
|
Java
import java.util.ArrayList;
import java.util.Collections;
public class CountPairs {
static int countPairs(ArrayList<Integer> arr, int K) {
int count = 0 ;
Collections.sort(arr);
for ( int i = 0 ; i < arr.size(); i++) {
if (K % arr.get(i) == 0 ) {
int left = i + 1 , right = arr.size() - 1 ;
while (left <= right) {
int mid = left + (right - left) / 2 ;
if (arr.get(mid) == K / arr.get(i)) {
count++;
break ;
} else if (arr.get(mid) < K / arr.get(i)) {
left = mid + 1 ;
} else {
right = mid - 1 ;
}
}
}
}
return count;
}
public static void main(String[] args) {
ArrayList<Integer> arr = new ArrayList<Integer>();
arr.add( 1 );
arr.add( 5 );
arr.add( 3 );
arr.add( 4 );
arr.add( 2 );
int K = 3 ;
int count = countPairs(arr, K);
System.out.println( "Number of distinct pairs with product " + K + " is " + count);
arr.clear();
arr.add( 1 );
arr.add( 2 );
arr.add( 16 );
arr.add( 4 );
arr.add( 4 );
K = 16 ;
count = countPairs(arr, K);
System.out.println( "Number of distinct pairs with product " + K + " is " + count);
arr.clear();
arr.add( 2 );
arr.add( 3 );
arr.add( 5 );
arr.add( 6 );
arr.add( 4 );
K = 9 ;
count = countPairs(arr, K);
System.out.println( "Number of distinct pairs with product " + K + " is " + count);
}
}
|
Python
def count_pairs(arr, K):
count = 0
arr.sort()
for i in range ( len (arr)):
if K % arr[i] = = 0 :
left, right = i + 1 , len (arr) - 1
while left < = right:
mid = left + (right - left) / / 2
if arr[mid] = = K / / arr[i]:
count + = 1
break
elif arr[mid] < K / / arr[i]:
left = mid + 1
else :
right = mid - 1
return count
if __name__ = = "__main__" :
arr = [ 1 , 5 , 3 , 4 , 2 ]
K = 3
count = count_pairs(arr, K)
print ( "Number of distinct pairs with product" ,
K, "is" , count)
arr = [ 1 , 2 , 16 , 4 , 4 ]
K = 16
count = count_pairs(arr, K)
print ( "Number of distinct pairs with product" ,
K, "is" , count)
arr = [ 2 , 3 , 5 , 6 , 4 ]
K = 9
count = count_pairs(arr, K)
print ( "Number of distinct pairs with product" ,
K, "is" , count)
|
C#
using System;
using System.Collections.Generic;
class GFG
{
static int CountPairs(List< int > arr, int K)
{
int count = 0;
arr.Sort();
for ( int i = 0; i < arr.Count; i++)
{
if (K % arr[i] == 0)
{
int left = i + 1;
int right = arr.Count - 1;
while (left <= right)
{
int mid = left + (right - left) / 2;
if (arr[mid] == K / arr[i])
{
count++;
break ;
}
else if (arr[mid] < K / arr[i])
{
left = mid + 1;
}
else
{
right = mid - 1;
}
}
}
}
return count;
}
static void Main()
{
List< int > arr = new List< int > { 1, 5, 3, 4, 2 };
int K = 3;
int count = CountPairs(arr, K);
Console.WriteLine( "Number of distinct pairs with product " + K + " is " + count);
arr = new List< int > { 1, 2, 16, 4, 4 };
K = 16;
count = CountPairs(arr, K);
Console.WriteLine( "Number of distinct pairs with product " + K + " is " + count);
arr = new List< int > { 2, 3, 5, 6, 4 };
K = 9;
count = CountPairs(arr, K);
Console.WriteLine( "Number of distinct pairs with product " + K + " is " + count);
}
}
|
Javascript
function CountPairs(arr, K) {
let count = 0;
arr.sort((a, b) => a - b);
for (let i = 0; i < arr.length; i++) {
if (K % arr[i] === 0) {
let left = i + 1, right = arr.length - 1;
while (left <= right) {
let mid = Math.floor((left + right) / 2);
if (arr[mid] === K / arr[i]) {
count++;
break ;
} else if (arr[mid] < K / arr[i]) {
left = mid + 1;
} else {
right = mid - 1;
}
}
}
}
return count;
}
let arr = [1, 5, 3, 4, 2];
let K = 3;
let count = CountPairs(arr, K);
console.log( "Number of distinct pairs with product " + K + " is " + count);
arr = [1, 2, 16, 4, 4];
K = 16;
count = CountPairs(arr, K);
console.log( "Number of distinct pairs with product " + K + " is " + count);
arr = [2, 3, 5, 6, 4];
K = 9;
count = CountPairs(arr, K);
console.log( "Number of distinct pairs with product " + K + " is " + count);
|
Output
Number of distinct pairs with product 3 is 1
Number of distinct pairs with product 16 is 2
Number of distinct pairs with product 9 is 0
Time complexity :O(n log n), where n is the length of the input array.
Space complexity: O(1), since we are not using any extra data structures besides the input array
Last Updated :
04 Oct, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...