Skip to content
Related Articles

Related Articles

Kth smallest element in an array that contains A[i] exactly B[i] times

View Discussion
Improve Article
Save Article
  • Difficulty Level : Basic
  • Last Updated : 13 Jul, 2021

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>

Output: 

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

 


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!