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++
// C++ code for the approach #include <bits/stdc++.h> using namespace std; // Function to count pairs with product equal to K int countPairsWithProductK( int arr[], int n, int k) { int count = 0; // Traverse through all possible pairs of the array for ( int i = 0; i < n; i++) { for ( int j = i + 1; j < n; j++) { // Check if the product of the current pair is equal to K if (arr[i] * arr[j] == k) { count++; } } } // Return the count of pairs with product equal to K return count; } // Driver's code int main() { int arr[] = { 1, 2, 16, 4, 4, 4, 8 }; int n = sizeof (arr) / sizeof (arr[0]); int k = 16; // Function Call int result = countPairsWithProductK(arr, n, k); // Print the result cout << result << endl; return 0; } |
Java
import java.util.*; public class Main { // Function to count pairs with product equal to K static int countPairsWithProductK( int [] arr, int k) { int count = 0 ; int n = arr.length; // Traverse through all possible pairs of the array for ( int i = 0 ; i < n; i++) { for ( int j = i + 1 ; j < n; j++) { // Check if the product of the current pair is equal to K if (arr[i] * arr[j] == k) { count++; } } } // Return the count of pairs with product equal to K return count; } // Driver's code public static void main(String[] args) { int [] arr = { 1 , 2 , 16 , 4 , 4 , 4 , 8 }; int k = 16 ; // Function Call int result = countPairsWithProductK(arr, k); // Print the result System.out.println(result); } } |
Python3
# Function to count pairs with product equal to K def countPairsWithProductK(arr, k): count = 0 n = len (arr) # Traverse through all possible pairs of the array for i in range (n): for j in range (i + 1 , n): # Check if the product of the current pair is equal to K if arr[i] * arr[j] = = k: count + = 1 # Return the count of pairs with product equal to K return count # Driver's code arr = [ 1 , 2 , 16 , 4 , 4 , 4 , 8 ] k = 16 # Function Call result = countPairsWithProductK(arr, k) # Print the result print (result) |
C#
using System; class CountPairsWithProductK { // Function to count pairs with product equal to K static int CountPairs( int [] arr, int n, int k) { int count = 0; // Traverse through all possible pairs of the array for ( int i = 0; i < n; i++) { for ( int j = i + 1; j < n; j++) { // Check if the product of the current pair // is equal to K if (arr[i] * arr[j] == k) { count++; } } } // Return the count of pairs with product equal to K return count; } // Driver program to test CountPairs static void Main() { int [] arr = { 1, 2, 16, 4, 4, 4, 8 }; int n = arr.Length; int k = 16; // Function Call int result = CountPairs(arr, n, k); // Print the result Console.WriteLine(result); } } |
5
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
// C++ program for the above approach #include <bits/stdc++.h> using namespace std; // Function to count // the total number of pairs int countPairsWithProductK( int arr[], int n, int k) { int count = 0; // Initialize hashmap. unordered_map< int , int > mp; // Insert array elements to hashmap 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 k is not power of two if (index >= 0 && ((index - ( int )(index)) == 0) && mp.find(k / arr[i]) != mp.end() && (index != arr[i])) { count += mp[arr[i]] * mp[index]; // After counting erase the element mp.erase(arr[i]); mp.erase(index); } // If k is power of 2 if (index >= 0 && ((index - ( int )(index)) == 0) && mp.find(k / arr[i]) != mp.end() && (index == arr[i])) { // Pair count count += (mp[arr[i]] * (mp[arr[i]] - 1)) / 2; // After counting erase the element; mp.erase(arr[i]); } } return count; } // Driver Code 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
// Java program for the above approach import java.util.*; class GFG{ // Function to count // the total number of pairs static int countPairsWithProductK( int arr[], int n, int k) { int count = 0 ; // Initialize hashmap. HashMap<Integer,Integer> mp = new HashMap<Integer,Integer>(); // Insert array elements to hashmap 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 k is not power of two if (index >= 0 && ((index - ( int )(index)) == 0 ) && mp.containsKey(k / arr[i]) && (index != arr[i])) { count += mp.get(arr[i]) * mp.get(index); // After counting erase the element mp.remove(arr[i]); mp.remove(index); } // If k is power of 2 if (index >= 0 && ((index - ( int )(index)) == 0 ) && mp.containsKey(k / arr[i]) && (index == arr[i])) { // Pair count count += (mp.get(arr[i]) * (mp.get(arr[i]) - 1 )) / 2 ; // After counting erase the element; mp.remove(arr[i]); } } return count; } // Driver Code 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)); } } // This code is contributed by 29AjayKumar |
Python3
# Python 3 program for the above approach from collections import defaultdict # Function to count # the total number of pairs def countPairsWithProductK(arr, n, k): count = 0 # Initialize hashmap. mp = defaultdict( int ) # Insert array elements to hashmap for i in range (n): mp[arr[i]] + = 1 for i in range (n): index = 1.0 * k / arr[i] # If k is not power of two if (index > = 0 and ((index - ( int )(index)) = = 0 ) and (k / arr[i]) in mp and (index ! = arr[i])): count + = mp[arr[i]] * mp[index] # After counting erase the element del mp[arr[i]] del mp[index] # If k is power of 2 if (index > = 0 and ((index - ( int )(index)) = = 0 ) and (k / arr[i]) in mp and (index = = arr[i])): # Pair count count + = ((mp[arr[i]] * (mp[arr[i]] - 1 )) / 2 ) # After counting erase the element; del mp[arr[i]] return count # Driver Code if __name__ = = "__main__" : arr = [ 1 , 2 , 16 , 4 , 4 , 4 , 8 ] N = len (arr) K = 16 print ( int (countPairsWithProductK(arr, N, K))) # This code is contributed by ukasp. |
C#
// C# program for the above approach using System; using System.Collections.Generic; public class GFG{ // Function to count // the total number of pairs static int countPairsWithProductK( int []arr, int n, int k) { int count = 0; // Initialize hashmap. Dictionary< int , int > mp = new Dictionary< int , int >(); // Insert array elements to hashmap 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 k is not power of two if (index >= 0 && ((index - ( int )(index)) == 0) && mp.ContainsKey(k / arr[i]) && (index != arr[i])) { count += mp[arr[i]] * mp[index]; // After counting erase the element mp.Remove(arr[i]); mp.Remove(index); } // If k is power of 2 if (index >= 0 && ((index - ( int )(index)) == 0) && mp.ContainsKey(k / arr[i]) && (index == arr[i])) { // Pair count count += (mp[arr[i]] * (mp[arr[i]] - 1)) / 2; // After counting erase the element; mp.Remove(arr[i]); } } return count; } // Driver Code 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)); } } // This code is contributed by Rajput-Ji |
Javascript
<script> // JavaScript code for the above approach // Function to count // the total number of pairs function countPairsWithProductK( arr, n, k) { let count = 0; // Initialize hashmap. let mp = new Map(); // Insert array elements to hashmap 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 k is not power of two if (index >= 0 && ((index - Math.floor(index)) == 0) && mp.has(k / arr[i]) && (index != arr[i])) { count += mp.get(arr[i]) * mp.get(index); // After counting erase the element mp. delete (arr[i]); mp. delete (index); } // If k is power of 2 if (index >= 0 && ((index - Math.floor(index)) == 0) && mp.has(k / arr[i]) && (index == arr[i])) { // Pair count count += (mp.get(arr[i]) * (mp.get(arr[i]) - 1)) / 2; // After counting erase the element; mp. delete (arr[i]); } } return count; } // Driver Code let arr = [1, 2, 16, 4, 4, 4, 8]; let N = arr.length; let K = 16; document.write(countPairsWithProductK(arr, N, K)); // This code is contributed by Potta Lokesh </script> |
5
Time Complexity: O(N)
Auxiliary Space: O(N)
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!