Open In App

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:
Explanation: 
There is only one pair (1, 3) with product = K = 3.



Input: arr[] = {1, 2, 16, 4, 4}, K = 16 
Output:
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.

Below is the implementation of the above approach:




// C++ program to count the number of pairs
// whose product is equal to K
 
#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;
    // count stores the final answer
 
    for (int i = 0; i < n; i++) {
 
        // check if element is not already seen and k/arr[i]
        // is present in ust
        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;
}
 
// Driver code
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 program to count the number of pairs
// whose product is equal to K
     
class GFG
{
    static int MAX = 100000;
     
    // Function to count the number of pairs
    // whose product is equal to K
    static int countPairsWithProductK(int arr[], int n, int k)
    {
        // Initialize the count
        int count = 0;
        int i;
 
        // Initialize empty hashmap.
        boolean hashmap[] = new boolean[MAX];
         
        // Insert array elements to hashmap
        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];
         
            // Checking if the index is a whole number
            // and present in the hashmap
            if (index >= 0
                && ((index - (int)(index)) == 0)
                && hashmap[k / x])
         
                count++;
            hashmap[x] = false;
        }
        return count;
    }
     
    // Driver code
    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 program to count the number of pairs
# whose product is equal to K
MAX = 100000;
 
# Function to count the number of pairs
# whose product is equal to K
def countPairsWithProductK(arr, n, k) :
 
    # Initialize the count
    count = 0;
 
    # Initialize empty hashmap.
    hashmap = [False]*MAX ;
 
    # Insert array elements to hashmap
    for i in range(n) :
        hashmap[arr[i]] = True;
 
    for i in range(n) :
        x = arr[i];
 
        index = 1.0 * k / arr[i];
 
        # Checking if the index is a whole number
        # and present in the hashmap
        if (index >= 0
            and ((index - int(index)) == 0)
            and hashmap[k // x]) :
 
                count += 1;
         
        hashmap[x] = False;
     
    return count;
 
# Driver code
if __name__ == "__main__" :
    arr = [ 1, 5, 3, 4, 2 ];
    N = len(arr);
    K = 3;
 
    print(countPairsWithProductK(arr, N, K));
 
# This code is contributed by AnkitRai01




// C# program to count the number of pairs
// whose product is equal to K    
using System;
 
class GFG
{
    static int MAX = 100000;
      
    // Function to count the number of pairs
    // whose product is equal to K
    static int countPairsWithProductK(int []arr, int n, int k)
    {
        // Initialize the count
        int count = 0;
        int i;
  
        // Initialize empty hashmap.
        bool []hashmap = new bool[MAX];
          
        // Insert array elements to hashmap
        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];
          
            // Checking if the index is a whole number
            // and present in the hashmap
            if (index >= 0
                && ((index - (int)(index)) == 0)
                && hashmap[k / x])
          
                count++;
            hashmap[x] = false;
        }
        return count;
    }
      
    // Driver code
    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));        
    }
}
 
// This code is contributed by 29AjayKumar




<script>
 
// JavaScript program to count the number of pairs
// whose product is equal to K
 
    let MAX = 100000;
     
    // Function to count the number of pairs
    // whose product is equal to K
    function countPairsWithProductK(arr,n,k)
    {
        // Initialize the count
        let count = 0;
        let i;
  
        // Initialize empty hashmap.
        let hashmap = new Array(MAX);
          
        // Insert array elements to hashmap
        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];
          
            // Checking if the index is a whole number
            // and present in the hashmap
            if (index >= 0
                && ((index - Math.floor(index)) == 0)
                && hashmap[k / x])
          
                count++;
            hashmap[x] = false;
        }
        return count;
    }
     
    // Driver code
    let arr=[1, 5, 3, 4, 2];
    let N = arr.length;
    let K = 3;
    document.write(countPairsWithProductK(arr, N, K));
 
// This code is contributed by rag2127
 
</script>

Output
1






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..




#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;
}




import java.util.Arrays;
 
public class CountPairs {
 
    // Function to count all distinct pairs
    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) {
 
            // Update the value of count
            if (arr[left] * arr[right] == k) {
                count++;
 
                // Update the value of
                // left and right
                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 the total count
        return count;
    }
 
    // Driver Code
    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);
    }
}




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)




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);
  }
}
 
// This code is contributed by user_dtewbxkn77n




function countPairs(arr, n, k) {
  // Sort the array in ascending order
  arr.sort((a, b) => a - b);
  let count = 0;
  let left = 0;
  let right = n - 1;
  // Loop until the left less than right pointers
  while (left < right) {
    // If the product of the left and right elements is equal to k,
    // increment the count and move both pointers towards the center
    if (arr[left] * arr[right] === k) {
      count++;
      left++;
      right--;
      // Skip any duplicate elements to avoid counting
      // the same pair more than once
      while (left < right && arr[left] === arr[left - 1]) {
        left++;
      }
      while (left < right && arr[right] === arr[right + 1]) {
        right--;
      }
    }
    // If the product is less than k, move the left pointer towards the center
    else if (arr[left] * arr[right] < k) {
      left++;
    }
    // If the product is greater than k, move the right pointer towards the center
    else {
      right--;
    }
  }
  return count;
}
 
// Driver code
const arr = [1, 5, 3, 4, 2];   // Input taken
const n = arr.length;
const k = 3;
const pairs = countPairs(arr, n, k);
console.log(pairs);

Output
1






 Time Complexity: O(NlogN)
Auxiliary Space: O(1)

Approach 3(using Binary Search)

The idea is to use binary search

Algorithm




#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()); // Step 1: Sort the input array in non-decreasing order
 
    for (int i = 0; i < arr.size(); i++) {
        if (K % arr[i] == 0) { // Check if K is divisible by arr[i]
            int left = i + 1, right = arr.size() - 1;
            while (left <= right) { // Step 3: Binary search for K/arr[i] in the right subarray
                int mid = left + (right - left) / 2;
                if (arr[mid] == K / arr[i]) { // Found a pair with product equal to K
                    count++;
                    break;
                }
                else if (arr[mid] < K / arr[i]) { // K/arr[i] is in the right half of the array
                    left = mid + 1;
                }
                else { // K/arr[i] is in the left half of the array
                    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; // Expected output: 1
 
    arr = {1, 2, 16, 4, 4};
    K = 16;
    count = count_pairs(arr, K);
    cout << "Number of distinct pairs with product " << K << " is " << count << endl; // Expected output: 2
 
    arr = {2, 3, 5, 6, 4};
    K = 9;
    count = count_pairs(arr, K);
    cout << "Number of distinct pairs with product " << K << " is " << count << endl; // Expected output: 0
 
    return 0;
}




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); // Step 1: Sort the input array in non-decreasing order
 
        for (int i = 0; i < arr.size(); i++) {
            if (K % arr.get(i) == 0) { // Check if K is divisible by arr.get(i)
                int left = i + 1, right = arr.size() - 1;
                while (left <= right) {
                    // Step 3: Binary search for K/arr.get(i) in the right subarray
                    int mid = left + (right - left) / 2;
                    // Found a pair with product equal to K
                    if (arr.get(mid) == K / arr.get(i)) {
                        count++;
                        break;
                    } else if (arr.get(mid) < K / arr.get(i)) {
                        // K/arr.get(i) is in the right half of the array
                        left = mid + 1;
                    } else { // K/arr.get(i) is in the left half of the array
                        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);
    }
}




def count_pairs(arr, K):
    count = 0
    arr.sort()  # Step 1: Sort the input list in non-decreasing order
 
    for i in range(len(arr)):
        if K % arr[i] == 0# Check if K is divisible by arr[i]
            left, right = i + 1, len(arr) - 1
            # Step 3: Binary search for K/arr[i] in the right subarray
            while left <= right:
                mid = left + (right - left) // 2
                if arr[mid] == K // arr[i]:  # Found a pair with product equal to K
                    count += 1
                    break
                elif arr[mid] < K // arr[i]:  # K/arr[i] is in the right half of the list
                    left = mid + 1
                else# K/arr[i] is in the left half of the list
                    right = mid - 1
    return count
 
 
# Main function
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)  # Expected output: 1
 
    arr = [1, 2, 16, 4, 4]
    K = 16
    count = count_pairs(arr, K)
    print("Number of distinct pairs with product",
          K, "is", count)  # Expected output: 2
 
    arr = [2, 3, 5, 6, 4]
    K = 9
    count = count_pairs(arr, K)
    print("Number of distinct pairs with product",
          K, "is", count)  # Expected output: 0




using System;
using System.Collections.Generic;
 
class GFG
{
    static int CountPairs(List<int> arr, int K)
    {
        int count = 0;
        arr.Sort();
      // Step 1: Sort the input list in non-decreasing order
        for (int i = 0; i < arr.Count; i++)
        {
            if (K % arr[i] == 0)
              // Check if K is divisible by arr[i]
            {
                int left = i + 1;
                int right = arr.Count - 1;
                while (left <= right)
                  // Step 3: Binary search for K/arr[i] in the right subarray
                {
                    int mid = left + (right - left) / 2;
                    if (arr[mid] == K / arr[i])
                      // Found a pair with product equal to K
                    {
                        count++;
                        break;
                    }
                    else if (arr[mid] < K / arr[i])
                      // K/arr[i] is in the right half of the list
                    {
                        left = mid + 1;
                    }
                    else
                      // K/arr[i] is in the left half of the list
                    {
                        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);
      // Expected output: 1
        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);
      // Expected output: 2
        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);
      // Expected output: 0
    }
}




function CountPairs(arr, K) {
    let count = 0;
    arr.sort((a, b) => a - b); // Step 1: Sort the input array in non-decreasing order
    for (let i = 0; i < arr.length; i++) {
        if (K % arr[i] === 0) { // Check if K is divisible by arr[i]
            let left = i + 1, right = arr.length - 1;
            while (left <= right) { // Step 3: Binary search for K/arr[i] in the right subarray
                let mid = Math.floor((left + right) / 2);
                if (arr[mid] === K / arr[i]) { // Found a pair with product equal to K
                    count++;
                    break;
                } else if (arr[mid] < K / arr[i]) { // K/arr[i] is in the right half of the array
                    left = mid + 1;
                } else { // K/arr[i] is in the left half of the array
                    right = mid - 1;
                }
            }
        }
    }
    return count;
}
// Test cases
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); // Expected output: 1
arr = [1, 2, 16, 4, 4];
K = 16;
count = CountPairs(arr, K);
console.log("Number of distinct pairs with product " + K + " is " + count); // Expected output: 2
arr = [2, 3, 5, 6, 4];
K = 9;
count = CountPairs(arr, K);
console.log("Number of distinct pairs with product " + K + " is " + count); // Expected output: 0

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


Article Tags :