text: Kth smallest element in an array that contains A [ i ] exactly B [ i ] times | C # 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
code: using System ; class GFG { 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 ; Console . Write ( KthSmallest ( A , B , N , K ) ) ; } }