Count all possible pairs in given Array with product K
Given an integer array arr[] of size N and a positive integer K, the task is to count all the pairs in the array with a product equal to K.
Examples:
Input: arr[] = {1, 2, 16, 4, 4, 4, 8 }, K=16
Output: 5
Explanation: Possible pairs are (1, 16), (2, 8), (4, 4), (4, 4), (4, 4)
Input: arr[] = {1, 10, 20, 10, 4, 5, 5, 2 }, K=20
Output: 5
Explanation: Possible pairs are (1, 20), (2, 10), (2, 10), (4, 5), (4, 5)
Naive Approach:
The naive approach for the problem is to run two nested loops to generate each possible pair and then for each pair generated check their product value. If their product comes out to be same as K then increment the count.
Algorithm:
- Initialize a variable count as 0.
- Traverse the array from index i=0 to i=N-1.
- For each i, traverse the array from index j=i+1 to j=N-1.
- For each pair (i,j), check if their product is equal to K.
- If their product is equal to K, increment the count.
- After completing the loops, return the count.
Below is the implementation of the approach:
C++
#include <bits/stdc++.h>
using namespace std;
int countPairsWithProductK( int arr[], int n, int k) {
int count = 0;
for ( int i = 0; i < n; i++) {
for ( int j = i + 1; j < n; j++) {
if (arr[i] * arr[j] == k) {
count++;
}
}
}
return count;
}
int main() {
int arr[] = { 1, 2, 16, 4, 4, 4, 8 };
int n = sizeof (arr) / sizeof (arr[0]);
int k = 16;
int result = countPairsWithProductK(arr, n, k);
cout << result << endl;
return 0;
}
|
Java
import java.util.*;
public class Main {
static int countPairsWithProductK( int [] arr, int k) {
int count = 0 ;
int n = arr.length;
for ( int i = 0 ; i < n; i++) {
for ( int j = i + 1 ; j < n; j++) {
if (arr[i] * arr[j] == k) {
count++;
}
}
}
return count;
}
public static void main(String[] args) {
int [] arr = { 1 , 2 , 16 , 4 , 4 , 4 , 8 };
int k = 16 ;
int result = countPairsWithProductK(arr, k);
System.out.println(result);
}
}
|
Python3
def countPairsWithProductK(arr, k):
count = 0
n = len (arr)
for i in range (n):
for j in range (i + 1 , n):
if arr[i] * arr[j] = = k:
count + = 1
return count
arr = [ 1 , 2 , 16 , 4 , 4 , 4 , 8 ]
k = 16
result = countPairsWithProductK(arr, k)
print (result)
|
C#
using System;
class CountPairsWithProductK {
static int CountPairs( int [] arr, int n, int k)
{
int count = 0;
for ( int i = 0; i < n; i++) {
for ( int j = i + 1; j < n; j++) {
if (arr[i] * arr[j] == k) {
count++;
}
}
}
return count;
}
static void Main()
{
int [] arr = { 1, 2, 16, 4, 4, 4, 8 };
int n = arr.Length;
int k = 16;
int result = CountPairs(arr, n, k);
Console.WriteLine(result);
}
}
|
Javascript
function countPairsWithProductK(arr, k) {
let count = 0;
const n = arr.length;
for (let i = 0; i < n; i++) {
for (let j = i + 1; j < n; j++) {
if (arr[i] * arr[j] === k) {
count++;
}
}
}
return count;
}
const arr = [1, 2, 16, 4, 4, 4, 8];
const k = 16;
const result = countPairsWithProductK(arr, k);
console.log(result);
|
Time Complexity: O(N*N) because two nested loops are executing. Here, N is size of input array.
Space Complexity: O(1) as no extra space has been used.
Approach: The idea is to use hashing to store the elements and check if K/arr[i] exists in the array or not using the map and increase the count accordingly.
Follow the steps below to solve the problem:
- Initialize the variable count as 0 to store the answer.
- Initialize the unordered_map<int, int> mp[].
- Iterate over the range [0, N) using the variable i and store the frequencies of all elements of the array arr[] in the map mp[].
- Iterate over the range [0, N) using the variable i and perform the following tasks:
- Initialize the variable index as K/arr[i].
- If K is not a power of 2 and index is present in map mp[] then increase the value of count by mp[arr[i]]*mp[index] and erase both of them from the map mp[].
- If K is a power of 2 and index is present in map mp[] then increase the value of count by mp[index]*(mp[index]-1)/2 and erase it from the map mp[].
- After performing the above steps, print the value of count as the answer.
Below is the implementation of the above approach.
C++14
#include <bits/stdc++.h>
using namespace std;
int countPairsWithProductK(
int arr[], int n, int k)
{
int count = 0;
unordered_map< int , int > mp;
for ( int i = 0; i < n; i++) {
mp[arr[i]]++;
}
for ( int i = 0; i < n; i++) {
double index = 1.0 * k / arr[i];
if (index >= 0
&& ((index - ( int )(index)) == 0)
&& mp.find(k / arr[i]) != mp.end()
&& (index != arr[i])) {
count += mp[arr[i]] * mp[index];
mp.erase(arr[i]);
mp.erase(index);
}
if (index >= 0
&& ((index - ( int )(index)) == 0)
&& mp.find(k / arr[i]) != mp.end()
&& (index == arr[i])) {
count += (mp[arr[i]]
* (mp[arr[i]] - 1))
/ 2;
mp.erase(arr[i]);
}
}
return count;
}
int main()
{
int arr[] = { 1, 2, 16, 4, 4, 4, 8 };
int N = sizeof (arr) / sizeof (arr[0]);
int K = 16;
cout << countPairsWithProductK(arr, N, K);
return 0;
}
|
Java
import java.util.*;
class GFG{
static int countPairsWithProductK(
int arr[], int n, int k)
{
int count = 0 ;
HashMap<Integer,Integer> mp = new HashMap<Integer,Integer>();
for ( int i = 0 ; i < n; i++) {
if (mp.containsKey(arr[i])){
mp.put(arr[i], mp.get(arr[i])+ 1 );
} else {
mp.put(arr[i], 1 );
}
}
for ( int i = 0 ; i < n; i++) {
int index = ( int ) ( 1.0 * k / arr[i]);
if (index >= 0
&& ((index - ( int )(index)) == 0 )
&& mp.containsKey(k / arr[i])
&& (index != arr[i])) {
count += mp.get(arr[i]) * mp.get(index);
mp.remove(arr[i]);
mp.remove(index);
}
if (index >= 0
&& ((index - ( int )(index)) == 0 )
&& mp.containsKey(k / arr[i])
&& (index == arr[i])) {
count += (mp.get(arr[i])
* (mp.get(arr[i]) - 1 ))
/ 2 ;
mp.remove(arr[i]);
}
}
return count;
}
public static void main(String[] args)
{
int arr[] = { 1 , 2 , 16 , 4 , 4 , 4 , 8 };
int N = arr.length;
int K = 16 ;
System.out.print(countPairsWithProductK(arr, N, K));
}
}
|
Python3
from collections import defaultdict
def countPairsWithProductK(arr, n, k):
count = 0
mp = defaultdict( int )
for i in range (n):
mp[arr[i]] + = 1
for i in range (n):
index = 1.0 * k / arr[i]
if (index > = 0
and ((index - ( int )(index)) = = 0 )
and (k / arr[i]) in mp
and (index ! = arr[i])):
count + = mp[arr[i]] * mp[index]
del mp[arr[i]]
del mp[index]
if (index > = 0
and ((index - ( int )(index)) = = 0 )
and (k / arr[i]) in mp
and (index = = arr[i])):
count + = ((mp[arr[i]]
* (mp[arr[i]] - 1 )) / 2 )
del mp[arr[i]]
return count
if __name__ = = "__main__" :
arr = [ 1 , 2 , 16 , 4 , 4 , 4 , 8 ]
N = len (arr)
K = 16
print ( int (countPairsWithProductK(arr, N, K)))
|
C#
using System;
using System.Collections.Generic;
public class GFG{
static int countPairsWithProductK(
int []arr, int n, int k)
{
int count = 0;
Dictionary< int , int > mp = new Dictionary< int , int >();
for ( int i = 0; i < n; i++) {
if (mp.ContainsKey(arr[i])){
mp[arr[i]] = mp[arr[i]]+1;
} else {
mp.Add(arr[i], 1);
}
}
for ( int i = 0; i < n; i++) {
int index = ( int ) (1.0 * k / arr[i]);
if (index >= 0
&& ((index - ( int )(index)) == 0)
&& mp.ContainsKey(k / arr[i])
&& (index != arr[i])) {
count += mp[arr[i]] * mp[index];
mp.Remove(arr[i]);
mp.Remove(index);
}
if (index >= 0
&& ((index - ( int )(index)) == 0)
&& mp.ContainsKey(k / arr[i])
&& (index == arr[i])) {
count += (mp[arr[i]]
* (mp[arr[i]] - 1))
/ 2;
mp.Remove(arr[i]);
}
}
return count;
}
public static void Main(String[] args)
{
int []arr = { 1, 2, 16, 4, 4, 4, 8 };
int N = arr.Length;
int K = 16;
Console.Write(countPairsWithProductK(arr, N, K));
}
}
|
Javascript
<script>
function countPairsWithProductK(
arr, n, k) {
let count = 0;
let mp = new Map();
for (let i = 0; i < n; i++) {
if (mp.has(arr[i])) {
mp.set(arr[i], mp.get(arr[i]) + 1);
}
else {
mp.set(arr[i], 1);
}
}
for (let i = 0; i < n; i++) {
let index = 1.0 * k / arr[i];
if (index >= 0
&& ((index - Math.floor(index)) == 0)
&& mp.has(k / arr[i])
&& (index != arr[i])) {
count += mp.get(arr[i]) * mp.get(index);
mp. delete (arr[i]);
mp. delete (index);
}
if (index >= 0
&& ((index - Math.floor(index)) == 0)
&& mp.has(k / arr[i])
&& (index == arr[i])) {
count += (mp.get(arr[i])
* (mp.get(arr[i]) - 1))
/ 2;
mp. delete (arr[i]);
}
}
return count;
}
let arr = [1, 2, 16, 4, 4, 4, 8];
let N = arr.length;
let K = 16;
document.write(countPairsWithProductK(arr, N, K));
</script>
|
Time Complexity: O(N)
Auxiliary Space: O(N)
Last Updated :
07 Dec, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...