Given two arrays A[] and B[] consisting of N positive integers and an integer K, the task is to find the Kth smallest element in the array formed by taking the ith element from the array A[] exactly B[i] times. If there exists no such element, then print -1.
Examples:
Input: K = 4, A[] = {1, 2, 3}, B[] = {1, 2, 3}Â
Output: 3
Explanation:
The array obtained by taking A[0], B[0] (= 1) time, A[1], B[1] (= 2) times, A[2], B[2]( = 3) Â times is {1, 2, 2, 3, 3, 3}. Therefore, the 4th element of the array is 3.Input: K = 4, A[] = {3, 4, 5}, B[] = {2, 1, 3}Â
Output: 3
Explanation:The array formed is {3, 3, 4, 5, 5, 5}. Therefore, the 4th element of the array i.e 5.
Naive Approach: The simplest approach is to iterate over the range [0, N – 1] and push the element at the ith index of the array, B[i] times into the new array. Finally, print the Kth element of the obtained array after sorting the array in ascending order.
Time Complexity: O(N*log(N)), where N is the number of elements in the new array.
Auxiliary Space: O(N)
Efficient Approach: The above approach can be optimized by using a frequency array to keep the count of every element. Follow the steps below to solve the problem:
- Find the maximum element of the array A[] and store it in a variable, say M.
- Initialize an array, say freq[] of size M + 1 with {0}, to store the frequency of every element.
- Iterate in the range [0, N-1] using the variable i:Â
- Add B[i] in freq[A[i]].Â
- Initialize a variable, say sum as 0, to store the prefix sum up to a particular index.
- Iterate over the range [0, N – 1] using a variable, say i:Â
- Add freq[i] in sum.
- If sum is greater than or equal to K, then return i.
- Finally, return -1.
Below is the implementation of the above approach:
C++
// C++ program for the above approach #include <bits/stdc++.h> using namespace std; Â
// Function to find the Kth smallest element // that contains A[i] exactly B[i] times int KthSmallest( int A[], int B[], int N, int K) { Â
    int M = 0; Â
    // Traverse the given array     for ( int i = 0; i < N; i++) { Â
        M = max(A[i], M);     } Â
    // Stores the frequency     // of every elements     int freq[M + 1] = { 0 }; Â
    // Traverse the given array     for ( int i = 0; i < N; i++) {         freq[A[i]] += B[i];     } Â
    // Initialize a variable to     // store the prefix sums     int sum = 0; Â
    // Iterate over the range [0, M]     for ( int i = 0; i <= M; i++) { Â
        // Increment sum by freq[i]         sum += freq[i]; Â
        // If sum is greater         // than or equal to K         if (sum >= K) { Â
            // Return the current             // element as answer             return i;         }     }     // Return -1     return -1; } Â
// Driver Code int main() { Â
    // Given Input     int A[] = { 3, 4, 5 };     int B[] = { 2, 1, 3 };     int N = sizeof (A) / sizeof (A[0]);     int K = 4; Â
    // Function call     cout << KthSmallest(A, B, N, K);     return 0; } |
Java
// Java program for the above approach public class GFG_JAVA { Â
    // Function to find the Kth smallest element     // that contains A[i] exactly B[i] times     static int KthSmallest( int A[], int B[], int N, int K)     { Â
        int M = 0 ; Â
        // Traverse the given array         for ( int i = 0 ; i < N; i++) { Â
            M = Math.max(A[i], M);         } Â
        // Stores the frequency         // of every elements         int freq[] = new int [M + 1 ]; Â
        // Traverse the given array         for ( int i = 0 ; i < N; i++) {             freq[A[i]] += B[i];         } Â
        // Initialize a variable to         // store the prefix sums         int sum = 0 ; Â
        // Iterate over the range [0, M]         for ( int i = 0 ; i <= M; i++) { Â
            // Increment sum by freq[i]             sum += freq[i]; Â
            // If sum is greater             // than or equal to K             if (sum >= K) { Â
                // Return the current                 // element as answer                 return i;             }         }         // Return -1         return - 1 ;     } Â
    // Driver code     public static void main(String[] args)     { // Given Input         int A[] = { 3 , 4 , 5 };         int B[] = { 2 , 1 , 3 };         int N = A.length;         int K = 4 ; Â
        // Function call         System.out.println(KthSmallest(A, B, N, K));     } } // This code is contributed by abhinavjain194 |
Python3
# Python3 program for the above approach Â
# Function to find the Kth smallest element # that contains A[i] exactly B[i] times def KthSmallest(A, B, N, K): Â
    M = 0 Â
    # Traverse the given array     for i in range (N):         M = max (A[i], M) Â
    # Stores the frequency     # of every elements     freq = [ 0 ] * (M + 1 ) Â
    # Traverse the given array     for i in range (N):         freq[A[i]] + = B[i] Â
    # Initialize a variable to     # store the prefix sums     sum = 0 Â
    # Iterate over the range [0, M]     for i in range (M + 1 ): Â
        # Increment sum by freq[i]         sum + = freq[i] Â
        # If sum is greater         # than or equal to K         if ( sum > = K): Â
            # Return the current             # element as answer             return i                  # Return -1     return - 1 Â
# Driver Code if __name__ = = "__main__" : Â
    # Given Input     A = [ 3 , 4 , 5 ]     B = [ 2 , 1 , 3 ]     N = len (A)     K = 4 Â
    # Function call     print (KthSmallest(A, B, N, K))     # This code is contributed by AnkThon |
C#
// C# program for the above approach using System; Â
class GFG{ Â
// Function to find the Kth smallest element // that contains A[i] exactly B[i] times static int KthSmallest( int []A, int []B, Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â int N, int K) { Â Â Â Â int M = 0; Â
    // Traverse the given array     for ( int i = 0; i < N; i++)     {         M = Math.Max(A[i], M);     } Â
    // Stores the frequency     // of every elements     int []freq = new int [M + 1]; Â
    // Traverse the given array     for ( int i = 0; i < N; i++)     {         freq[A[i]] += B[i];     } Â
    // Initialize a variable to     // store the prefix sums     int sum = 0; Â
    // Iterate over the range [0, M]     for ( int i = 0; i <= M; i++)     {                  // Increment sum by freq[i]         sum += freq[i]; Â
        // If sum is greater         // than or equal to K         if (sum >= K)         {                          // Return the current             // element as answer             return i;         }     }          // Return -1     return -1; } Â
// Driver code public static void Main(String[] args) {           // Given Input     int []A = { 3, 4, 5 };     int []B = { 2, 1, 3 };     int N = A.Length;     int K = 4; Â
    // Function call     Console.Write(KthSmallest(A, B, N, K)); } } Â
// This code is contributed by shivanisinghss2110 |
Javascript
<script> Â Â Â // JavaScript program for the above approach Â
    // Function to find the Kth smallest element     // that contains A[i] exactly B[i] times     function KthSmallest(A, B, N, K)     { Â
        let M = 0; Â
        // Traverse the given array         for (let i = 0; i < N; i++) { Â
            M = Math.max(A[i], M);         } Â
        // Stores the frequency         // of every elements         let freq = Array.from({length: M + 1}, (_, i) => 0); Â
        // Traverse the given array         for (let i = 0; i < N; i++) {             freq[A[i]] += B[i];         } Â
        // Initialize a variable to         // store the prefix sums         let sum = 0; Â
        // Iterate over the range [0, M]         for (let i = 0; i <= M; i++) { Â
            // Increment sum by freq[i]             sum += freq[i]; Â
            // If sum is greater             // than or equal to K             if (sum >= K) { Â
                // Return the current                 // element as answer                 return i;             }         }         // Return -1         return -1;     } Â
// Driver Code Â
    // Given Input         let A = [ 3, 4, 5 ];         let B = [ 2, 1, 3 ];         let N = A.length;         let K = 4; Â
        // Function call         document.write(KthSmallest(A, B, N, K));          </script> |
5
Â
Time Complexity: O(N), where N is the size of arrays A[] and B[].
Auxiliary Space: O(M), where M is the maximum element of the array A[].
Â
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!