Given an array arr[] of size N and an integer K, the task is to find the Kth number from the product array.
Note: A product array prod[] of an array is a sorted array of size (N*(N-1))/2 in which each element is formed as prod[k] = arr[i] * arr[j], where 0 ? i < j < N.
Examples:Â
Â
Input: arr[] = {-4, -2, 3, 3}, K = 3Â
Output: -6Â
Final prod[] array = {-12, -12, -6, -6, 8, 9}Â
where prod[K] = -6
Input: arr[] = {5, 4, 3, 2, -1, 0, 0}, K = 20Â
Output: 15Â
Â
Â
Naive Approach: Generate the prod[] array by iterating the given array twice and then sort the prod[] array and find the Kth element from the array.Â
Time Complexity: O(N2 * log(N))
Efficient Approach: The number of negative, zero, and positive pairs can be easily determined, so you can tell whether the answer is negative, zero, or positive. If the answer is negative, it is possible to measure the number of pairs that are greater than or equal to K by selecting a negative number and a positive number one by one, so the answer is obtained using a binary search. The answer is exactly the same when the answer is positive, but consider choosing the same element twice, and subtracting it will count each pair exactly twice.
Below is the implementation of the above approach:
Â
C++
// C++ implementation to find the// Kth number in the list formed// from product of any two numbers// in the array and sorting themÂ
#include <bits/stdc++.h>using namespace std;Â
// Function to find number of pairsbool check(long long x,           vector<int>& pos,           vector<int>& neg, int k){    long long pairs = 0;Â
    int p = neg.size() - 1;    int nn = neg.size() - 1;    int pp = pos.size() - 1;Â
    // Negative and Negative    for (int i = 0; i < neg.size(); i++) {        while (p >= 0 and neg[i] * neg[p] <= x)            p--;Â
        // Add Possible Pairs        pairs += min(nn - p, nn - i);    }Â
    // Positive and Positive    p = 0;    for (int i = pos.size() - 1; i >= 0; i--) {        while (p < pos.size() and pos[i] * pos[p] <= x)            p++;Â
        // Add Possible pairs        pairs += min(p, i);    }Â
    // Negative and Positive    p = pos.size() - 1;    for (int i = neg.size() - 1;         i >= 0;         i--) {        while (p >= 0 and neg[i] * pos[p] <= x)            p--;Â
        // Add Possible pairs        pairs += pp - p;    }Â
    return (pairs >= k);}Â
// Function to find the kth// element in the listlong long kth_element(int a[],                      int n, int k){    vector<int> pos, neg;Â
    // Separate Positive and    // Negative elements    for (int i = 0; i < n; i++) {        if (a[i] >= 0)            pos.push_back(a[i]);        else            neg.push_back(a[i]);    }Â
    // Sort the Elements    sort(pos.begin(), pos.end());    sort(neg.begin(), neg.end());Â
    long long l = -1e18,              ans = 0, r = 1e18;Â
    // Binary search    while (l <= r) {        long long mid = (l + r) >> 1;        if (check(mid, pos, neg, k)) {            ans = mid;            r = mid - 1;        }        else            l = mid + 1;    }Â
    // Return the required answer    return ans;}Â
// Driver codeint main(){Â Â Â Â int a[] = { -4, -2, 3, 3 }, k = 3;Â
    int n = sizeof(a) / sizeof(a[0]);Â
    // Function call    cout << kth_element(a, n, k);Â
    return 0;} |
Java
// Java implementation to find the // Kth number in the list formed // from product of any two numbers // in the array and sorting themimport java.util.*; Â
class GFG {         // Function to find number of pairs     static boolean check(int x, Vector pos, Vector neg, int k)     {         int pairs = 0;              int p = neg.size() - 1;         int nn = neg.size() - 1;         int pp = pos.size() - 1;              // Negative and Negative         for (int i = 0; i < neg.size(); i++)         {             while ((p >= 0) && ((int)neg.get(i) *                     (int)neg.get(p) <= x))                 p--;                  // Add Possible Pairs             pairs += Math.min(nn - p, nn - i);         }              // Positive and Positive         p = 0;         for (int i = pos.size() - 1; i >= 0; i--)        {             while ((p < pos.size()) && ((int)pos.get(i) *                     (int)pos.get(p) <= x))                 p++;                  // Add Possible pairs             pairs += Math.min(p, i);         }              // Negative and Positive         p = pos.size() - 1;         for (int i = neg.size() - 1;             i >= 0; i--) {             while ((p >= 0) && ((int)neg.get(i) *                     (int)pos.get(p) <= x))                 p--;                  // Add Possible pairs             pairs += pp - p;         }              return (pairs >= k);     }          // Function to find the kth     // element in the list     static int kth_element(int a[], int n, int k)     {         Vector pos = new Vector();        Vector neg = new Vector();;              // Separate Positive and         // Negative elements         for (int i = 0; i < n; i++)        {             if (a[i] >= 0)                 pos.add(a[i]);             else                neg.add(a[i]);         }              // Sort the Elements         //sort(pos.begin(), pos.end());         //sort(neg.begin(), neg.end());         Collections.sort(pos);        Collections.sort(neg);             int l = (int)-1e8, ans = 0, r = (int)1e8;              // Binary search         while (l <= r)        {             int mid = (l + r) >> 1;             if (check(mid, pos, neg, k))             {                 ans = mid;                 r = mid - 1;             }             else                l = mid + 1;         }              // Return the required answer         return ans;     }          // Driver code     public static void main (String[] args)    {         int a[] = { -4, -2, 3, 3 }, k = 3;         int n = a.length;              // Function call         System.out.println(kth_element(a, n, k));     } }Â
// This code is contributed by AnkitRai01 |
Python3
# Python3 implementation to find the# Kth number in the list formed# from product of any two numbers# in the array and sorting themÂ
# Function to find number of pairsdef check(x, pos, neg, k):Â Â Â Â pairs = 0Â
    p = len(neg) - 1    nn = len(neg) - 1    pp = len(pos) - 1Â
    # Negative and Negative    for i in range(len(neg)):        while (p >= 0 and neg[i] * neg[p] <= x):            p -= 1Â
        # Add Possible Pairs        pairs += min(nn - p, nn - i)Â
    # Positive and Positive    p = 0    for i in range(len(pos) - 1, -1, -1):        while (p < len(pos) and pos[i] * pos[p] <= x):            p += 1Â
        # Add Possible pairs        pairs += min(p, i)Â
    # Negative and Positive    p = len(pos) - 1    for i in range(len(neg) - 1, -1, -1):        while (p >= 0 and neg[i] * pos[p] <= x):            p -= 1Â
        # Add Possible pairs        pairs += pp - pÂ
    return (pairs >= k)Â
# Function to find the kth# element in the listdef kth_element(a, n, k):Â Â Â Â pos, neg = [],[]Â
    # Separate Positive and    # Negative elements    for i in range(n):        if (a[i] >= 0):            pos.append(a[i])        else:            neg.append(a[i])Â
    # Sort the Elements    pos = sorted(pos)    neg = sorted(neg)Â
    l = -10**18    ans = 0    r = 10**18Â
    # Binary search    while (l <= r):        mid = (l + r) >> 1        if (check(mid, pos, neg, k)):            ans = mid            r = mid - 1        else:            l = mid + 1Â
    # Return the required answer    return ansÂ
# Driver codea = [-4, -2, 3, 3]k = 3Â
n = len(a)Â
# Function callprint(kth_element(a, n, k))Â
# This code is contributed by mohit kumar 29 |
C#
// C# implementation to find the // Kth number in the list formed // from product of any two numbers // in the array and sorting themusing System;using System.Collections.Generic;Â
class GFG {         // Function to find number of pairs     static bool check(int x, List<int> pos, List<int> neg, int k)     {         int pairs = 0;              int p = neg.Count - 1;         int nn = neg.Count - 1;         int pp = pos.Count - 1;              // Negative and Negative         for (int i = 0; i < neg.Count; i++)         {             while ((p >= 0) && ((int)neg[i] *                     (int)neg[p] <= x))                 p--;                  // Add Possible Pairs             pairs += Math.Min(nn - p, nn - i);         }              // Positive and Positive         p = 0;         for (int i = pos.Count - 1; i >= 0; i--)        {             while ((p < pos.Count) && ((int)pos[i] *                     (int)pos[p] <= x))                 p++;                  // Add Possible pairs             pairs += Math.Min(p, i);         }              // Negative and Positive         p = pos.Count - 1;         for (int i = neg.Count - 1; i >= 0; i--)         {             while ((p >= 0) && ((int)neg[i] *                     (int)pos[p] <= x))                 p--;                  // Add Possible pairs             pairs += pp - p;         }              return (pairs >= k);     }          // Function to find the kth     // element in the list     static int kth_element(int []a, int n, int k)     {         List<int> pos = new List<int>();        List<int> neg = new List<int>();;              // Separate Positive and         // Negative elements         for (int i = 0; i < n; i++)        {             if (a[i] >= 0)                 pos.Add(a[i]);             else                neg.Add(a[i]);         }              // Sort the Elements         //sort(pos.begin(), pos.end());         //sort(neg.begin(), neg.end());         pos.Sort();        neg.Sort();             int l = (int)-1e8, ans = 0, r = (int)1e8;              // Binary search         while (l <= r)        {             int mid = (l + r) >> 1;             if (check(mid, pos, neg, k))             {                 ans = mid;                 r = mid - 1;             }             else                l = mid + 1;         }              // Return the required answer         return ans;     }          // Driver code     public static void Main(String[] args)    {         int []a = { -4, -2, 3, 3 };        int k = 3;         int n = a.Length;              // Function call         Console.WriteLine(kth_element(a, n, k));     } }Â
// This code is contributed by 29AjayKumar |
Javascript
<script>    // Javascript implementation to find the     // Kth number in the list formed     // from product of any two numbers     // in the array and sorting them         // Function to find number of pairs     function check(x, pos, neg, k)     {         let pairs = 0;                let p = neg.length - 1;         let nn = neg.length - 1;         let pp = pos.length - 1;                // Negative and Negative         for (let i = 0; i < neg.length; i++)         {             while ((p >= 0) && (neg[i] * neg[p] <= x))                 p--;                    // Add Possible Pairs             pairs += Math.min(nn - p, nn - i);         }                // Positive and Positive         p = 0;         for (let i = pos.length - 1; i >= 0; i--)        {             while ((p < pos.length) && (pos[i] * pos[p] <= x))                 p++;                    // Add Possible pairs             pairs += Math.min(p, i);         }                // Negative and Positive         p = pos.length - 1;         for (let i = neg.length - 1; i >= 0; i--)         {             while ((p >= 0) && (neg[i] * pos[p] <= x))                 p--;                    // Add Possible pairs             pairs += pp - p;         }                return (pairs >= k);     }            // Function to find the kth     // element in the list     function kth_element(a, n, k)     {         let pos = [];        let neg = [];                // Separate Positive and         // Negative elements         for (let i = 0; i < n; i++)        {             if (a[i] >= 0)                 pos.push(a[i]);             else                neg.push(a[i]);         }                // Sort the Elements         //sort(pos.begin(), pos.end());         //sort(neg.begin(), neg.end());         pos.sort(function(a, b){return a - b});        neg.sort(function(a, b){return a - b});               let l = -1e8, ans = 0, r = 1e8;                // Binary search         while (l <= r)        {             let mid = (l + r) >> 1;             if (check(mid, pos, neg, k))             {                 ans = mid;                 r = mid - 1;             }             else                l = mid + 1;         }                // Return the required answer         return ans;     }         let a = [ -4, -2, 3, 3 ];    let k = 3;     let n = a.length; Â
    // Function call     document.write(kth_element(a, n, k)); Â
// This code is contributed by divyesh072019.</script> |
-6
Â
Time Complexity: O(n logn)
Space Complexity: O(1)
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!

… [Trackback]
[…] Information on that Topic: geeksforgeeks.org/find-kth-number-from-sorted-array-formed-by-multiplying-any-two-numbers-in-the-array/ […]