Kth smallest element in an array that contains A [ i ] exactly B [ i ] times | Java program for the above approach ; Function to find the Kth smallest element that contains A [ i ] exactly B [ i ] times ; Traverse the given array ; Stores the frequency of every elements ; Traverse the given array ; Initialize a variable to store the prefix sums ; Iterate over the range [ 0 , M ] ; Increment sum by freq [ i ] ; If sum is greater than or equal to K ; Return the current element as answer ; Return - 1 ; Driver code ; { Given Input ; Function call
public class GFG_JAVA { static int KthSmallest ( int A [ ] , int B [ ] , int N , int K ) { int M = 0 ; for ( int i = 0 ; i < N ; i ++ ) { M = Math . max ( A [ i ] , M ) ; } int freq [ ] = new int [ M + 1 ] ; for ( int i = 0 ; i < N ; i ++ ) { freq [ A [ i ] ] += B [ i ] ; } int sum = 0 ; for ( int i = 0 ; i <= M ; i ++ ) { sum += freq [ i ] ; if ( sum >= K ) { return i ; } } return - 1 ; } public static void main ( String [ ] args ) int A [ ] = { 3 , 4 , 5 } ; int B [ ] = { 2 , 1 , 3 } ; int N = A . length ; int K = 4 ; System . out . println ( KthSmallest ( A , B , N , K ) ) ; } }